Javascript 在javascript中访问ajax POST响应

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

Accessing ajax POST response in javascript

javascriptjqueryasp.net

提问by mike44

I'm making ajax POST request from javascript function:

我正在从 javascript 函数发出 ajax POST 请求:

function UpdateMetrics() {
   $.ajax({
              type: "POST",
              url: "MyHandler.ashx?Param1=value1",
              data: "{}",
              contentType: "text/json; charset=utf-8",
              dataType: "text",
              success: function (msg) {
                  var jsonUpdatedData = msg;
                  ...
              }
          });
}

From my handler, I'm sending json string with:

从我的处理程序,我发送 json 字符串:

context.Response.write(json);

I think I'll get it in msg.

我想我会得到它msg

I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:

我还想发送其他字符串(计数)。所以我试图将标题信息与 json 数据一起使用。所以我添加了这一行:

context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count)); 

If this is right way to do it, how can I access it in my successfunction?

如果这是正确的方法,我如何在我的success函数中访问它?

回答by Xymostech

To access headers in your successfunction, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.

要访问success函数中的标头,请向函数添加另外 2 个参数,即状态代码和 jqXHR 对象,您可以在api.jquery.com 上阅读相关文档。

So, your function should look like:

所以,你的函数应该是这样的:

success: function (msg, status, jqXHR) {
    var jsonUpdatedData = msg;
    ...
}

However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.

但是,正如评论中指出的那样,最好不要使用标头发送数据。您可能应该将它包含在您发送的 json 中。

You also need to tell jQuery to interpret the response as json by setting

您还需要通过设置告诉 jQuery 将响应解释为 json

dataType: "json"

Otherwise, it will just be returned to you as text.

否则,它只会作为文本返回给您。

回答by Sridhar Narasimhan

Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.

您可以使用 getResponseHeader 方法实现在 ajax post 成功中获取标头数据的要求,请参阅以下代码片段。

function UpdateMetrics() {
var callback =  $.ajax({
          type: "POST",
          url: "MyHandler.ashx?Param1=value1",
          data: "{}",
          contentType: "text/json; charset=utf-8",
          dataType: "text",
          success: function (msg) {

          var jsonUpdatedData = msg;
        var headerdata = callback.getResponseHeader("MaxCount"); 
// Where MaxCount is name provided in the header.
   ...
          }
      });
}

Thanks

谢谢