javascript 访问 Ajax 响应数据

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

Accessing Ajax Response Data

javascriptjqueryjson

提问by daniel__

I have this code that works well:

我有这个运行良好的代码:

{"livre":"empty_name"}

    $.ajax({
        url: "sent.php",
        type: "post",
        dataType: "json",
        data: formdata,
        success: function (data) {
            switch (data.livre) {
                  case 'empty_name':

                  break;
        }
    });

but when i try this code (i need the id), the case "empty name" didn't works. The option selected will be the default case:

但是当我尝试这个代码(我需要 id)时,“空名称”的情况不起作用。选择的选项将是默认情况:

{"id":"","livre":"empty_name"}

    $.ajax({
        url: "sent.php",
        type: "post",
        dataType: "json",
        data: formdata,
        success: function (id, data) {
            switch (data.livre) {
                 case 'empty_name':

                 break;
        }
    });

Why? and how can be solved? thanks

为什么?以及如何解决?谢谢

采纳答案by dontGoPlastic

If I understand correctly with the object up top being the JSON response, I think you want this...

如果我正确理解顶部的对象是 JSON 响应,我想你想要这个......

{"id":"","livre":"empty_name"}

$.ajax({
    url: "sent.php",
    type: "post",
    dataType: "json",
    data: formdata,
    success: function (data) {
        var jsonId = data.id;
    }
});

The dataparameter of the successcallback contains your response (in this case, JSON data). You access your JSON content there.

回调的data参数success包含您的响应(在本例中为 JSON 数据)。您可以在那里访问您的 JSON 内容。

回答by Quintin Robinson

You just need to understand how the data is being returned. In this case datais the object containing all the fields. Your success callback would continue to look like success: function(data)the code you need to change is in the method block itself.

您只需要了解数据是如何返回的。在这种情况下data是包含所有字段的对象。您的成功回调将继续看起来像success: function(data)您需要更改的代码在方法块本身中。

$.ajax({
    url: "sent.php",
    type: "post",
    dataType: "json",
    data: formdata,
    success: function (data) {
        var id = data.id; //ID lives in data.
        switch (data.livre) {
    }
});

Since you redefined the function, the switch will fail because in the example posted livrewill reside in the idobject and notin the dataobject.

既然你重新定义的功能,因为在本例中张贴的开关将无法livre将驻留在id对象,并没有data对象。