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

问题描述 投票:0回答:1

我正在从 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" }

从上面的回复中,我想得到

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 yii2-advanced-app
1个回答
0
投票

您需要了解服务器响应的结构,才能找到其中的正确参数。

响应包含一个带有四个键的

Object

{ data, message, transactionid, status }

这是一个通用响应对象,其中包含

data
键中请求的信息以及有关响应本身的一些信息。

您对

Array
类型的数据字段的内容感兴趣,即内部可能有零到多个对象。在您的情况下,您很可能总是对数据数组中的第一个对象感兴趣(如果有)。这里,有一个
Object
,带有三个键:

{ 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
}
© www.soinside.com 2019 - 2024. All rights reserved.