簡體   English   中英

JSON / JQUERY / JS-從對象訪問屬性

[英]JSON/JQUERY/JS - Access properties from object

從我的PHP處理文件中,我收到一個object[object Object] ),並且我想通過data[0].errors等調用來訪問它的內容,但是所有嘗試似乎都對我失敗了。

我該如何實現?

對象的外觀如下:

" Array
(
    [success] => 
    [errors] => Array
        (
            [companyname] => Company name is required and must have 50 characters at most.
            [logo1] => Logo is required.
            [investment] => First investment amount is required.
            [investment1] => Investment value must be an integer.
            [payment] => Basic wage is required.
            [payment1] => Payment value must be an integer.
            [companytype] => Company type is required.
            [companytype2] => Something is wrong with your company type.
        )

)
"

我必須在控制台div中顯示這些errors ,以向用戶顯示他做錯了什么。

編輯:

這就是我console.log(data)時得到的: 控制台日志

這也是我的AJAX請求,以使一切變得清晰。

        $.ajax({
                type        : 'POST',
                url         : 'processcreatecompany.php',
                data        : formData,
                dataType    : 'json',
               contentType: false,
               processData: false,
                encode      : true
            }).done(function(data) {

                console.log(data);
            }).fail(function(data) {

                console.log(data);

        })

如預期的那樣,問題出在php部分...您正在執行對象的print_r ,該對象給出的輸出不是json

您應該使用json_encode返回$data對象/數組,所以不要

print_r($data['success']);
print_r($data['errors']);

您應該擁有(還應該添加內容類型標頭)

header('Content-Type: application/json');
echo json_encode($data);

以后的編輯:如果沒有標題,通常會在data.responseTexttext/plain形式獲得響應,就像在屏幕截圖中一樣,並且您將不得不“手工”進行JSON解析。 添加標頭使jQuery自動執行解析,並且您會將響應作為data.response<something I dont recall now>的對象。 data.response<something I dont recall now>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM