【问题标题】:Get json array output from php in javascript and detect if it's undefined在javascript中从php获取json数组输出并检测它是否未定义
【发布时间】:2021-07-05 21:06:20
【问题描述】:

我正在尝试从 php 文件中检索 json 输出并输出一个值。有人能告诉我如何检测值是否未定义以及如何访问数组中的值之一吗?

php response:
{"myObj":[{"userid":"9000","name":"Foo"},{"userid":"1000","name":"Bar"}]}

$.ajax({
    type: 'POST',
    url: 'reply.php',
    beforeSend: function (xhr) {
        if (xhr && xhr.overrideMimeType) {
            xhr.overrideMimeType('application/json;charset=utf-8');
        }
    },
    data: {
        "action": "getmyObj"
    },
    success: function (reply) {
    if (reply.myObj.length > 0) {
        for (i = 0; i < 3; i++){
            if (typeof reply.myObj[i].name === 'undefined') {
                console.log("Undefined");
            } else {
                alert(reply.myObj[i].name);
        }
    }
});

【问题讨论】:

  • 您遇到了什么错误?你的代码似乎正确

标签: javascript arrays json element


【解决方案1】:

你可以替换

for (i = 0; i < 3; i++){

for (i = 0; i < reply.myObj.length; i++){

这样它将根据有多少条目而不是静态3 次进行迭代,那么你可能甚至不必检查 prop 是否未定义(因为它是第三次迭代)

属性的检查应该很简单:

if (!reply.myObj[i].name) {
    console.log("Undefined");
} else {
    alert(reply.myObj[i].name);

因为上面提到的你可以确定reply.myObj[i]被定义了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 2021-02-09
    • 2019-04-05
    • 2012-07-05
    • 2019-03-25
    • 1970-01-01
    • 2015-09-27
    • 2020-05-14
    相关资源
    最近更新 更多