jQuery $.ajax request of dataType json 不会从 PHP 脚本中检索数据

2022-08-31 00:17:27

我一直在寻找解决方案,但我找不到任何有效的方法。我正在尝试从数据库中获取一堆数据,然后通过AJAX自动完成表单中的输入字段。为此,我决定使用json,因为为什么不呢,对吧?或者,我一直在想只是发回一个分隔的字符串,然后标记它,这在事后看来会容易得多,并且使我免于头痛......由于我决定使用json,我想我应该坚持下去,找出出了什么问题!发生的情况是,当执行get_member_function()时,在警报对话框中弹出一个错误,并显示“[对象对象]”。我也尝试过使用GET请求,并将contentType设置为“application/json;字符集=utf-8”。唉,没有骰子。任何人都可以建议我做错了什么吗?保重,皮奥特。

我的javascript/jQuery函数如下:

function get_member_info()
   {

   var url = "contents/php_scripts/admin_scripts.php"; 
   var id = $( "select[ name = member ] option:selected" ).val();

   $.ajax(
   {

      type: "POST",
      dataType: "json",
      url: url,
      data: { get_member: id },
      success: function( response ) 
      { 

          $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" );
          $( "input[ name = name ]" ).val( response.name );
          $( "input[ name = fname ]" ).val( response.fname );
          $( "input[ name = lname ]" ).val( response.lname );
          $( "input[ name = email ]" ).val( response.email );
          $( "input[ name = phone ]" ).val( response.phone );
          $( "input[ name = website ]" ).val( response.website );
          $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image );

      },
      error: function( error )
      {

         alert( error );

      }

   } );

}

“contents/php_scripts/admin_scripts.php”中的相关代码如下:

   if( isset( $_POST[ "get_member" ] ) )
   {

      $member_id = $_POST[ "get_member" ];
      $query = "select * from members where id = '$member_id'";

      $result = mysql_query( $query );

      $row = mysql_fetch_array( $result );

      $type = $row[ "type" ];
      $name = $row[ "name" ];
      $fname = $row[ "fname" ];
      $lname = $row[ "lname" ];
      $email = $row[ "email" ];
      $phone = $row[ "phone" ];
      $website = $row[ "website" ];
      $image = $row[ "image" ];

      $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image );

      echo json_encode( $json_arr );

   }

答案 1

我想我知道这个...

尝试使用 PHP 的 header() 函数将 JSON 作为 JSON 发送:

/**
 * Send as JSON
 */
header("Content-Type: application/json", true);

虽然你正在传递有效的JSON,但jQuery的$.ajax并不这么认为,因为它缺少标头。

jQuery曾经没有头文件很好,但它被改回了几个版本。

请确保您的脚本返回有效的 JSON。使用 FirebugGoogle Chrome 的开发者工具在控制台中检查请求的响应。

更新

您还需要更新代码以清理 $_POST,以避免 sql 注入攻击。以及提供一些错误捕获。

if (isset($_POST['get_member'])) {

    $member_id = mysql_real_escape_string ($_POST["get_member"]);

    $query = "SELECT * FROM `members` WHERE `id` = '" . $member_id . "';";

    if ($result = mysql_query( $query )) {

       $row = mysql_fetch_array($result);

       $type = $row['type'];
       $name = $row['name'];
       $fname = $row['fname'];
       $lname = $row['lname'];
       $email = $row['email'];
       $phone = $row['phone'];
       $website = $row['website'];
       $image = $row['image'];

       /* JSON Row */
       $json = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image );

    } else {

        /* Your Query Failed, use mysql_error to report why */
        $json = array('error' => 'MySQL Query Error');

    }

     /* Send as JSON */
     header("Content-Type: application/json", true);

    /* Return JSON */
    echo json_encode($json);

    /* Stop Execution */
    exit;

}

答案 2

尝试在获取数据时使用 jQuery.parseJSON。

type: "POST",
dataType: "json",
url: url,
data: { get_member: id },
success: function(data) { 
    response = jQuery.parseJSON(data);
    $("input[ name = type ]:eq(" + response.type + " )")
        .attr("checked", "checked");
    $("input[ name = name ]").val( response.name);
    $("input[ name = fname ]").val( response.fname);
    $("input[ name = lname ]").val( response.lname);
    $("input[ name = email ]").val( response.email);
    $("input[ name = phone ]").val( response.phone);
    $("input[ name = website ]").val( response.website);
    $("#admin_member_img")
        .attr("src", "images/member_images/" + response.image);
},
error: function(error) {
    alert(error);
}

推荐