Javascript 从 jQuery.get() 返回 responseText

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7598821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:51:52  来源:igfitidea点击:

return responseText from jQuery.get()

javascriptajaxjqueryget

提问by Yann Milin

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]"

我认为 msg 会被设置为 my_script.php 返回的文本,即 jqXHR 对象的 responseText。它显然不是这样工作的,因为 msg 总是设置为“[object XMLHttpRequest]”

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

有没有一种快速的 1 行方式来做我想做的事?

Thanks.

谢谢。

回答by Yann Milin

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:

我需要调用是同步的,$.get 速记函数总是异步的,所以我需要使用 $.ajax,像这样:

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.

我认为没有更好的方法可以做到这一点,谢谢您的回答。

回答by Vitor M

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.

如果由于某种原因响应是文本,则远程脚本可能会将内容类型更改为 JSON 之类的内容,因此 jQuery 会在输出给您之前尝试解析该字符串。

回答by njr101

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

返回值只是用于 ajax 请求的 jqXHR 对象。要获取响应数据,您需要注册一个回调。

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

回答by Dave Newton

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

响应文本在成功回调中可用;在那里做你需要做的事情。