当前查询的URL

I have an AJAX Web application where I want to have the URL to reflect what the current query is, in order to have a "permalink". For example a user enters "foobar" as a query in a search input, then http://example/search/ in the URL bar becomes updated to http://example/search/?foobar.

When trying to implement this with index.html as:

<script>
query = "foobar";
window.location.search = query;
</script>

Firstly this strangely sends the browser in an endless loop. What am I missing?

Changing window.location makes the browser reload that page.