json 如何在警报中显示 AJAX 响应消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24982226/
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-09-03 17:26:55  来源:igfitidea点击:

How to show AJAX response message in alert?

ajaxjson

提问by ShutterSoul

I am sending username and password as request parameter to the server in AJAX and trying to show the response message. But not able to showing the response message.In fiddler it is showing the response message. But while on the browser screen it is not showing.PLEASE somebody help me out where i am wrong or need to change anything.. I have written like this-

我将用户名和密码作为请求参数发送到 AJAX 中的服务器并尝试显示响应消息。但无法显示响应消息。在 fiddler 中,它显示响应消息。但是在浏览器屏幕上它没有显示。请有人帮我解决我错在哪里或需要更改任何内容..我是这样写的-

$(document).ready(function () {
  $("#btnCity").click(function () {
    $.ajax({
      type: "POST",
      url: "http://test.xyz.com/login",
      crossDomain: true,
      contentType: "application/json; charset=utf-8",
      data: { username: "abc", password: "1234" },
      dataType: "JSONP",
      jsonpCallback: 'jsonCallback',
      async: false,
      success: function (resdata) {
        alert(resdata);
      },
      error: function (result, status, err) {
        alert(result.responseText);
        alert(status.responseText);
        alert(err.Message);
      }
    });
  });
});

回答by ConcurrentHashMap

TL;DR: I guess the problem is on the server side of your code (that we don't know yet).

TL;DR:我猜问题出在你的代码的服务器端(我们还不知道)。

At first: I don't know why it fails for you. I've taken your code and ran it against a public available JSONP API, that returns the current IP of your system and it worked.

起初:我不知道为什么它对你来说失败了。我已经获取了您的代码并针对公共可用的 JSONP API 运行它,该 API 返回您系统的当前 IP 并且它工作正常。

Please try yourself using the URL: http://ip.jsontest.com/.

请尝试使用 URL: http://ip.jsontest.com/

So most probably, the server doesn't return the right response to the JSONP request. Have a look at the network tab in developer tools. With your current code, the answer of the server should be something like:

所以很可能,服务器没有向 JSONP 请求返回正确的响应。查看开发人员工具中的网络选项卡。使用您当前的代码,服务器的答案应该是这样的:

jsonCallback({'someResponseKeys': 'someResponseValue'});

Note: The header should contain Content-Type:application/javascript!

注意:标题应包含Content-Type:application/javascript!



BTW, even if this doesn't for now solve your problem - here are some tweaks, I'd like to advice to you:

顺便说一句,即使这暂时不能解决您的问题 - 这里有一些调整,我想给您建议:

  • Don't set asyncto false, at the documentation of jQuery.ajax()says:

    Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

  • You don't need to set a jsonpCallback, because jQuery will generate and handle (using the successfunction a random one for you. Quote from the docs:

    This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.

  • 不要设置async为 false,在jQuery.ajax()的文档中说:

    跨域请求和 dataType: "jsonp" 请求不支持同步操作。

  • 您不需要设置 a jsonpCallback,因为 jQuery 将生成和处理(使用该success函数为您随机生成一个。引自文档:

    将使用此值代替 jQuery 自动生成的随机名称。最好让 jQuery 生成一个唯一的名称,因为这样可以更轻松地管理请求并提供回调和错误处理。

So here comes my code:

所以这是我的代码:

$(document).ready(function () {
  $("#btnCity").click(function () {
    $.ajax({
      type: "POST",
      url: "http://ip.jsontest.com/",
      crossDomain: true,
      data: { username: "abc", password: "1234" },
      dataType: "JSONP",
      success: function (resdata) {
        console.log("success", resdata);
      },
      error: function (result, status, err) {
        console.log("error", result.responseText);
        console.log("error", status.responseText);
        console.log("error", err.Message);
      }
    });
  });
});

A working example can be found here.

可以在此处找到工作示例

Another solution, like Yonatan Ayalon suggested, can be done with a predefined function and then setting the jsonpCallbackexplicitly to the function that should be called.

另一种解决方案,如 Yonatan Ayalon 建议的那样,可以使用预定义的函数完成,然后将jsonpCallback显式设置为应该调用的函数。

回答by Yonatan Ayalon

if you see the response in Fiddler, it seems that the issue is in the callback function.

如果您在 Fiddler 中看到响应,则问题似乎出在回调函数中。

you are doing a jsonP call - which means that you need a callback function to "read" the response data.

您正在执行 jsonP 调用 - 这意味着您需要一个回调函数来“读取”响应数据。

Do you have a local function that calls "jsonCallback"?

你有一个调用“jsonCallback”的本地函数吗?

this is a simple jsonP request, which initiates the function "gotBack()" with the response data:

这是一个简单的 jsonP 请求,它使用响应数据启动函数“gotBack()”:

            function gotBack(data) {
                console.log(data);
            }
            $.ajax({
                url: 'http://test.xyz.com/login' + '?callback=?',
                type: "POST",
                data: formData,
                dataType: "jsonp",
                jsonpCallback: "gotBack"
            });

回答by Pradeepta

You can try with the following methods and close every instance of chrome browser in task manager, then open browser in web security disable mode by the command "chrome.exe --disable-web-security"

您可以尝试使用以下方法并在任务管理器中关闭所有 chrome 浏览器实例,然后通过命令“chrome.exe --disable-web-security”在网络安全禁用模式下打开浏览器

 success: function (resdata) {
        alert(resdata);
        alert(JSON.stringify(resdata));
    },

And the better option to debug the code using "debugger;"

以及使用“调试器”调试代码的更好选择;

success: function (resdata) {
            debugger;
            alert(resdata);
            alert(JSON.stringify(resdata));
        },