i've been doing a lot of ajax scripts and every time something seems to be different.
in this case i have a form that i want to post
<form id="sss">
<input id="qqq"/>
<input type="submit" id="s" href="Search!"/>
</form>
<div id="rrr"></div>
and
$('#s').click(function(){
$.ajax({
url: 'foo.php',
data: {
query: $('#q').val()
},
success: function(data) {
$('#rrr').html(data);
}
});
return false;
});
and
if(isset($_REQUEST['query'])){
print_r($_REQUEST['query']);
}
what happens is that in <div id="rrr"></div>
gets loaded the print开发者_高级运维_r($_REQUEST['query']);
and all the rest of the html page.
i only want to return $_REQUEST['query']
weird!?
any ideas? What this success: function(data){}
actually means?
Thanks
If you are requesting the same page that you are current displaying, then your if
statement doesn't stop processing, so the rest of the page is returned as well. You either need to die()
afterward, or (recommended) create a separate page entirely dedicated to handling AJAX requests. Here's an example of how to properly stop processing:
if (isset($_REQUEST['query'])) {
print_r($_REQUEST['query']);
die(); // stop processing.
}
In regards to your second point, I think you might be misunderstanding the technical details of what's actually happening here:
- Client requests
foo.php
from server. Server executesfoo.php
according to the logic in the page, and sends response output to browser. Browser renders the page. - Client sends AJAX request (which is nothing more than a request that happens asynchronously, i.e., separately from the browser loading a page) to
foo.php?query=...
- Server executes
foo.php?query=...
(just like it did in step (1)!), which causes the firstif
to trigger before returning the rest of the html in response, so the same page is returned except with the query output at the top (Try going directly tofoo.php?query=...
in your browser and I think you'll see what I mean). - However, instead of the response being rendered in the browser, since it was an AJAX request, the response is captured into a variable,
data
. - The callback
function success(data)
is executed, passing the exact output returned from the server as-is from the AJAX request (i.e., the variable contains the same as viewing the source offoo.php?query=...
in your browser), which is then processed according to your logic. In this case, you are dumping the contents into adiv
, so you see the output correctly.
Please take a moment to install and run Fiddler, so you can see the exact data that is flowing back and forth as you load the page in your browser, and then watch what happens as you make an AJAX call. Perhaps it will make the data flow and results you are getting much clearer.
Hope this helps!
精彩评论