开发者

jquery, ajax returning weird data?

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:

  1. Client requests foo.php from server. Server executes foo.php according to the logic in the page, and sends response output to browser. Browser renders the page.
  2. 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=...
  3. Server executes foo.php?query=... (just like it did in step (1)!), which causes the first if 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 to foo.php?query=... in your browser and I think you'll see what I mean).
  4. However, instead of the response being rendered in the browser, since it was an AJAX request, the response is captured into a variable, data.
  5. 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 of foo.php?query=... in your browser), which is then processed according to your logic. In this case, you are dumping the contents into a div, 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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜