如果接收到数组和对象,如何解析 jQuery 中 php 的数据

How to parse data from php in jQuery if received Array & Object

PHP:

header('Content-Type: application/json');
//Some code
$files_arr['BadIMG'][$i] = $fileName;
//Some code
$files_arr['GoodIMG'][$i] = $path;
//Some code
echo json_encode($files_arr);

JS:

success: function(response) {
    console.log(response.BadIMG);
    console.log(response.GoodIMG);
    for (var i = 0; i < response.GoodIMG.length; i++) {
        var src = response.GoodIMG[i];
        $('#fast-reply_textarea').focus().val($('#fast-reply_textarea').val() + '\n[img]https://url/' + src + '[/img]\n');
    }
}

如果从PHP只收到GoodIMG,一切正常,在#fast-reply_textarea成功添加图片链接:

console.log(response.BadIMG);
undefined
console.log(response.GoodIMG);
Array [ "1_Good.jpg", "2_Good.jpg" ]

但是如果从 PHP 收到 GoodIMG + BadIMG 没有插入 #fast-reply_textarea:

console.log(response.BadIMG);
Array [ "1_Bad.jpg", "2_Bad.jpg" ]

console.log(response.GoodIMG);
Object { 2: "1_Good.jpg", 3: "2_Good.jpg" }

如果来自 PHP 只收到 BadIMG:

console.log(response.BadIMG);
Array [ "1_Bad.jpg", "2_Bad.jpg" ]

console.log(response.GoodIMG);
undefined //With error:
Uncaught TypeError: can't access property "length", response.GoodIMG is undefined

如果收到 BadIMGGoodIMG 并添加 GoodIMG 链接,如何解析此数据在编辑器中? 对于 BadIMG 我将添加警报,例如:来自(计算所有图像)图像(BadIMG 的计数或名称)未上传。

您可以删除 PHP 数组中的 $i 索引。

$files_arr['BadIMG'][] = $fileName;
$files_arr['GoodIMG'][] = $path;

在这种情况下,两者都是数组,而不是对象。

另外,在JS中,你应该测试变量是否被定义。

success: function(response) {
    if (typeof response.GoodIMG !== "undefined") {
        for (var i = 0; i < response.GoodIMG.length; i++) {
            var src = response.GoodIMG[i];
            $('#fast-reply_textarea').focus().val($('#fast-reply_textarea').val() + '\n[img]https://url/' + src + '[/img]\n');
        }
    }
}