开发者

Data empty in jQuery.get() callback

$.get("http://localhost/test.php", (function(data){
    alert(data);
}))

The alert is empty. I'm new to this, and I can't see what I'm doin开发者_Go百科g wrong. Help?


It does work with a file:// URL but not http://? I smell same origin policy.

Are you opening the file with the jQuery in your browser via a file:// URL then trying to fetch via http://? Because your protocol and host have to match when you do Ajax.

Make sure that you're opening the file in your browser as http://localhost/index.php and not file://localhost/index.php. Then you should be able to fetch that file via http://localhost/test.php.


Perhaps you're not telling the code to run? Try putting it in $(document).ready() with

$(function() {
  $.get("http://localhost/test.php", function(data){
    alert(data);
  });
});

http://api.jquery.com/ready/


If you type http://locahost/test.php in your browser, do you get any data back?

There is no difference whether jquery gets the url or you do, the result should be the same.


Does test.php actually output something?

This works for me.


What is the mime-type of the response?

The doc says

The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.

So depending on the datatype of the data parameter to your callback, the alert may be trying to show you an object that doesn't translate readily to a string.


The callback function should be the third parameter to $.get:

 $.get("http://localhost/test.php", {}, (function(data){
     alert(data);
 }))


Okay, solved it: Works when the html file is in the webserver dir and called from localhost, doesn't work when the html is file://. This is inconvenient, but oh well. (it seems I can't mark my own answer as the solution until 2 days.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜