Correct way to read 'echo json_encode( )' from JQuery

后端 未结 5 1200
醉梦人生
醉梦人生 2021-01-05 10:09

I am using: echo json_encode($Response); to send an Associative array back to JQuery Ajax. Whenever I try to read each ID key value I get an undefined value. Please help me

相关标签:
5条回答
  • 2021-01-05 10:16

    You should set the mime type aswell, wich, according to this question is application/json. Then jQuery will understand the answer is a json element. To do it, you'd do the following:

    header('Content-Type: application/json');
    

    In your UpdateEditAStudent.php before printing anything.

    0 讨论(0)
  • 2021-01-05 10:16

    do something like this

    $Stuff = 'Hello world';
    
    $Success = true;
    $Content = $Stuff;
    
    $Response = array('Success' => $Success, 'Content' => $Content);
    echo json_encode($Response);
    
    0 讨论(0)
  • 2021-01-05 10:17

    You need to define the correct dataType or provide the correct header, as Lumbendil described.

    You can manually define the dataType to json, so your code would look like:

    $.ajax({  
       type: "GET",  
        url: "../pgs/UpdateEditAStudent.php", 
       data: "FirstName="+ sFirstName ,  
       dataType: "json",
       ...etc
    
    0 讨论(0)
  • 2021-01-05 10:21

    You don't have to add a header to the PHP file, just use this Jquery parseJSON function:

    Keep this PHP code as it is:

    $Stuff = 'Hello world';
    
    $Success = true;
    $Content = $Stuff;
    
    $Response = array('Success' => $Success, 'Content' => $Content);
    echo json_encode($Response);
    

    And for the JS:

    $.ajax({  
        type: "GET",
        url: "../pgs/UpdateEditAStudent.php",
        data: "FirstName="+ $('#student_first_name').val(),
    
        success: function(data){
            // Here is the tip
            var data = $.parseJSON(data);
    
            alert(data.Content);
        }
    });
    
    0 讨论(0)
  • 2021-01-05 10:22

    It's an array. You should probably do alert(data['Content']);.

    0 讨论(0)
提交回复
热议问题