簡體   English   中英

jQuery AJAX使用JSON Return調用PHP腳本

[英]jQuery AJAX Call to PHP Script with JSON Return

我一直在用一塊磚牆砸我的頭,我已經在stackoverflow上嘗試了大量的解決方案,但找不到一個有效的方法!

基本上當我發布我的AJAX時,PHP返回JSON,但AJAX顯示Undefined而不是值:

JS

  /* attach a submit handler to the form */
  $("#group").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /*clear result div*/
  $("#result").html('');

  /* get some values from elements on the page: */
  var val = $(this).serialize();

  /* Send the data using post and put the results in a div */
  $.ajax({
      url: "inc/group.ajax.php",
      type: "post",
      data: val,
  datatype: 'json',
      success: function(data){
            $('#result').html(data.status +':' + data.message);   
            $("#result").addClass('msg_notice');
            $("#result").fadeIn(1500);           
      },
      error:function(){
          $("#result").html('There was an error updating the settings');
          $("#result").addClass('msg_error');
          $("#result").fadeIn(1500);
      }   
    }); 
});

PHP

  $db = new DbConnector();
  $db->connect();
  $sql='SELECT grp.group_id, group_name, group_enabled, COUNT('.USER_TBL.'.id) AS users, grp.created, grp.updated '
        .'FROM '.GROUP_TBL.' grp '
        .'LEFT JOIN members USING(group_id) '
        .'WHERE grp.group_id ='.$group_id.' GROUP BY grp.group_id';

    $result = $db->query($sql);     
    $row = mysql_fetch_array($result);
    $users = $row['users'];
    if(!$users == '0'){
        $return["json"] = json_encode($return);
        echo json_encode(array('status' => 'error','message'=> 'There are users in this group'));
    }else{

        $sql2= 'DELETE FROM '.GROUP_TBL.' WHERE group_id='.$group_id.'';
        $result = $db->query($sql2);

        if(!$result){
            echo json_encode(array('status' => 'error','message'=> 'The group has not been removed'));
        }else{
            echo json_encode(array('status' => 'success','message'=> 'The group has been removed'));
        }
    }

來自firebug的JSON結果

{"status":"success","message":"success message"}

AJAX將JSON結果顯示為Undefined,我不知道為什么。 我試過顯示添加dataType='json'datatype='json' 我也嘗試將其更改為data.statusdata['status'] :盡管如此仍然沒有樂趣。

任何幫助將非常感激。

使其成為dataType而不是datatype

並在PHP中添加以下代碼,因為您的ajax請求期望json並且不會接受任何內容,但是json。

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

更正JSON和JSONP的內容類型

在firebug中可見的響應是文本數據。 如果響應是json,請檢查響應頭的Content-Type以驗證。 它應該是application/json for dataType:'json'text/html for dataType:'html'

我建議你使用:

var returnedData = JSON.parse(data);

將JSON字符串(如果它只是文本)轉換為JavaScript對象。

使用parseJSON jquery方法將字符串轉換為對象

var objData = jQuery.parseJSON(data);

現在你可以編寫代碼了

$('#result').html(objData .status +':' + objData .message);

嘗試從服務器發送內容類型標頭在回顯之前使用它

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

您的數據類型錯誤,請更改dataType的數據類型。

暫無
暫無

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

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