return responseText from jQuery.get()

亡梦爱人 提交于 2019-11-27 03:18:45

问题


I tried to do something like this :

var msg = $.get("my_script.php");

I thought msg would be set to the text returned by my_script.php,i.e. the responseText of the jqXHR object. It apparently doesn't work like that as msg is always set to "[object XMLHttpRequest]"

Is there a quick 1 line way to do what I want?

Thanks.


回答1:


After some testing, I ended up finding a solution.

I need the call to be synchronous, $.get shorthand function is always asynchonous, so I will need to use $.ajax, like this:

var msg = $.ajax({type: "GET", url: "my_script.php", async: false}).responseText;

I don't think there is a better way to do this, thanks for your answers.




回答2:


You can always use:

var msg;
$.get("my_script.php", function(text) {
  msg = text;
});

If for some reason the response is text, the remote script might be changing the content-type to something like JSON, and thus jQuery tries to parse the string before outputting to you.




回答3:


The return value is simply the jqXHR object used for the ajax request. To get the response data you need to register a callback.

$.get("my_script.php", function(data) {
  var msg = data;
  alert(msg);
});



回答4:


The response text is available in the success callback; do what you need to do with it there.



来源:https://stackoverflow.com/questions/7598821/return-responsetext-from-jquery-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!