dataType json的jQuery $ .ajax请求不会从PHP脚本中检索数据

时间:2011-02-28 21:01:00

标签: php jquery ajax json

我一直在寻找解决方案,但我找不到任何有效的方法。 我试图从数据库中获取一堆数据,然后通过表单中的AJAX自动完成输入字段。为此,我决定使用json,因为为什么不呢,对吧?另外,我一直在考虑发回一个分隔的字符串,然后将它标记出来,在后视中它会更容易并且让我免于头疼......因为我已经决定使用json,我想我应该坚持下去,找出问题所在! 发生的事情是,当执行get_member_function()时,警报对话框中会弹出一个错误,并显示“[object Object]”。我也尝试过使用GET请求,并将contentType设置为“application / json;字符集= UTF-8“。唉,没有骰子。任何人都可以建议我做错了什么?小心,Piotr。

我的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 );

   }

8 个答案:

答案 0 :(得分:24)

我想我知道这一个......

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

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

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

jQuery过去很好没有标题,但是它被改回了几个版本。

同时

确保您的脚本返回有效的JSON。使用FirebugGoogle Chrome's Developer Tools在控制台中检查请求的响应。

<强>更新

您还需要更新代码以清理$ _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;

}

答案 1 :(得分:9)

在获取数据时尝试使用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);
}

答案 2 :(得分:5)

$.ajax error函数有三个参数,而不是一个:

error: function(xhr, status, thrown)

你需要转储第二个和第三个参数来找到你的原因,而不是第一个。

答案 3 :(得分:2)

除了McHerbie的说明,如果您使用的是PHP 5.3,请尝试json_encode( $json_arr, JSON_FORCE_OBJECT );

答案 4 :(得分:1)

  session_start();
include('connection.php');

/* function msg($subjectname,$coursename,$sem)
    {
    return '{"subjectname":'.$subjectname.'"coursename":'.$coursename.'"sem":'.$sem.'}';
    }*/ 
$title_id=$_POST['title_id'];
$result=mysql_query("SELECT * FROM `video` WHERE id='$title_id'") or die(mysql_error());
$qr=mysql_fetch_array($result);
$subject=$qr['subject'];
$course=$qr['course'];
$resultes=mysql_query("SELECT * FROM course JOIN subject ON course.id='$course' AND subject.id='$subject'");
$qqr=mysql_fetch_array($resultes);
$subjectname=$qqr['subjectname'];
$coursename=$qqr['coursename'];
$sem=$qqr['sem'];
$json = array("subjectname" => $subjectname, "coursename" => $coursename, "sem" => $sem,);
header("Content-Type: application/json", true);
echo json_encode( $json_arr );


 $.ajax({type:"POST",    
                  dataType: "json",    
                   url:'select-title.php',
                   data:$('#studey-form').serialize(),
                   contentType: "application/json; charset=utf-8",
                   beforeSend: function(x) {
        if(x && x.overrideMimeType) {
            x.overrideMimeType("application/j-son;charset=UTF-8");
        }
    },
                   success:function(response)
                  {
                    var response=$.parseJSON(response)
                    alert(response.subjectname);
                    $('#course').html("<option>"+response.coursename+"</option>"); 
                    $('#subject').html("<option>"+response.subjectname+"</option>");

                  },
                  error: function( error,x,y)
                  {

                  alert( x,y );

              }
                   });

答案 5 :(得分:0)

如果您使用的是较新版本(超过1.3.x),您应该了解有关函数parseJSON的更多信息!我遇到了同样的问题。使用旧版本或更改代码

success=function(data){
  //something like this
  jQuery.parseJSON(data)
}

答案 6 :(得分:0)

Try this...  
  <script type="text/javascript">

    $(document).ready(function(){

    $("#find").click(function(){
        var username  = $("#username").val();
            $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'includes/find.php',
            data: 'username='+username,
            success: function( data ) {
            //in data you result will be available...
            response = jQuery.parseJSON(data);
//further code..
            },

    error: function(xhr, status, error) {
        alert(status);
        },
    dataType: 'text'

    });
        });

    });



    </script>

    <form name="Find User" id="userform" class="invoform" method="post" />

    <div id ="userdiv">
      <p>Name (Lastname, firstname):</p>
      </label>
      <input type="text" name="username" id="username" class="inputfield" />
      <input type="button" name="find" id="find" class="passwordsubmit" value="find" />
    </div>
    </form>
    <div id="userinfo"><b>info will be listed here.</b></div>

答案 7 :(得分:0)

嗯,这可能对某人有所帮助。我愚蠢到把var_dump('testing');放在我请求JSON的函数中以确保实际收到了请求。这显然也是预期json响应的一部分,并且dataType设置为json,请求失败。