首页 > 解决方案 > easyui 从 ajax 返回 undefined

问题描述

我提交表单,当我签入控制台时,它返回 JSON 数据。但我不能在 JSON 数据中使用对象。

$('#ff').form({
                type: 'POST',
                cache: false,
                url: base_url + 'Api/lapor/submit',
                dataType: 'json',
                iframe: false,
                onSubmit: function(param) {
                    param.id_item = sessionStorage.id_item;
                    param.token = sessionStorage.token;
                },
                onProgress: function(percent) {
                    $.messager.progress();
                },
                success: function(msg){
                  console.log(msg.status); //it will return undefined
                  $.messager.progress('close');
                },
                onLoadError: function(){
                    $.messager.alert('Error', 'Gagal', 'error');
                }
            });

我尝试console.log(msg)并返回 JSON 数据 控制台

标签: jqueryajaxjquery-easyui

解决方案


当您使用 记录返回消息console.log(msg.status);时,如果它写入结果,{message: "Data 1 telah disimpan", status: true}那么您可以使用msg.status或调用它msg['status']

但在您的情况下,它记录为{"message": "Data 1 telah disimpan", "status": true},因此您应该尝试使用"包含的 likemsg['"status"']msg["\"status\""]

var msg1 = {"message": "Data 1 telah disimpan", "status": true}
var msg2 = {'"message"': "Data 2 telah disimpan", '"status"': true}

function checkdata1() {
  console.log(msg1);
  alert(msg1.message);
}

function checkdata2() {
  console.log(msg2);
  alert(msg2['"message"'])
}
<btn onclick="checkdata1()">Check Data 1</btn>
<br/>
<btn onclick="checkdata2()">Check Data 2</btn>

更新msg1以下是使用记录时和msg2记录时的区别console.logdifference

Update 2 Because the return type of jeasyui $.form is a string, so you need to parse it first to a JSON / javascript object by using JSON.parse or the one found in the jeasyui docs section Handle submit response here


推荐阅读