无法在 Yii2 中使用 ajax 调用从 api 响应中获取数据

Unable to get data from api response using ajax call in Yii2

提问人:Moeez 提问时间:11/7/2023 更新时间:11/10/2023 访问量:32

问:

我正在发送来自 API 的请求以获取一些数据。

 $.ajax({
                    url: '$urlmsim',
                    method: 'POST',
                    headers: headers,
                    data: formData,
                    processData: false, // Prevent jQuery from processing the data
                    contentType: false, // Let the browser set the content type
                    success: function (imsi) {
                        // Handle and display the IMSI result
                        console.log(imsi);
                        
                        //$('#imsiResult').text('IMSI: ' + imsi);
                         //$('#metertosimmapping-imsi').val(imsi.msim_id);
                    },
                    error: function (error) {
                        console.error('MSIM API call failed: ' + JSON.stringify(error));
                    },
                    complete: function () {
                        // This function is called after the request is complete, whether it's successful or not
                        hideLoader(); // Hide the loader here
                    }   
                });

调用已成功进行,并且我能够在一个对象中接收响应,我可以在执行时在控制台中看到它。以下是回应console.log(imsi);

0: Object { global_device_id: "m98202315", msn: "2998202315", msim_id: "89410034222316193981" }

enter image description here

从上面的回复中,我想得到.我试图通过关注来获得msim_id

console.log(imsi.msim_id);这给了我undefined

console.log(imsi[0].msim_id);这给了我Uncaught TypeError: imsi[0] is undefined

我还尝试了以下方法

if (Array.isArray(imsi) && imsi.length > 0) {
var imsi_id = imsi[0].msim_id;
console.log(imsi_id);
} else {
console.log("imsi is not defined or is an empty array.");
}

但我正在得到imsi is not defined or is an empty array.

如何从此响应中获取所需的数据?

任何帮助将不胜感激。

php jquery ajax yii2-advanced-app

评论

2赞 Cyclonecode 11/7/2023
你不应该使用吗?imsi.data[0].msim_id

答:

0赞 DEAD10CC 11/10/2023 #1

您需要了解服务器响应的结构,以便对其中的正确参数进行寻址。

响应包含四个键:Object

{ data, message, transactionid, status }

这是一个常规响应对象,其中包含密钥中请求的信息以及有关响应本身的一些信息。data

您对数据类型为的数据字段的内容感兴趣,即内部可能有零到多个对象。在您的例子中,您很可能总是对数据数组中的第一个对象感兴趣(如果有的话)。在这里,有一个有三个键:ArrayObject

{ global_device_id, msn, msim_id }

因此,通过此层次结构从结果中检索msim_id的方法是

imsi.data[0].msim_id

如果你重命名你的变量,使它们更好地反映这种结构,并添加一些检查,你最好得到这个想法:

success: function (result) { // the generic result comes in
    var data = result.data; // we are interested in the data
    var imsi = data[0]; // the first element should be the imsi

    if (typeof imsi === undefined) { // make sure it is 
        // no imsi in response
        return;
    }
    
    console.log(imsi.msim_id) // here it is
}