dataType json 的 jQuery $.ajax 请求不会从 PHP 脚本中检索数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5147522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery $.ajax request of dataType json will not retrieve data from PHP script
提问by Piotr
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get_member_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr.
我一直在寻找解决方案,但找不到任何有效的方法。我试图从数据库中获取一堆数据,然后通过表单中的 AJAX 自动完成输入字段。为此,我决定使用 json,因为为什么不呢,对吧?或者,我一直在考虑只发回一个分隔的字符串,然后将其标记化,事后看来这会容易得多,而且让我免于头疼......不过既然我决定使用 json,我想我应该坚持下去,找出哪里出了问题!发生的情况是,当执行 get_member_function() 时,会在警告对话框中弹出错误并读取“[object Object]”。我也尝试过使用 GET 请求,并将 contentType 设置为“application/json;”。字符集=utf-8″。唉,没有骰子。谁能建议我做错了什么?保重,彼得。
My javascript/jQuery function is as follows:
我的 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 );
}
} );
}
and the relevant code in "contents/php_scripts/admin_scripts.php" is as follows:
而“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 );
}
回答by McHerbie
I think I know this one...
我想我知道这个...
Try sending your JSON as JSON by using PHP's header()function:
尝试使用 PHP 的header()函数将 JSON 作为 JSON 发送:
/**
* Send as JSON
*/
header("Content-Type: application/json", true);
Though you are passing valid JSON, jQuery's $.ajax doesn't think so because it's missing the header.
尽管您正在传递有效的 JSON,但 jQuery 的 $.ajax 并不这么认为,因为它缺少标头。
jQuery used to be fine without the header, but it was changed a few versions back.
jQuery 过去没有标题就很好,但它被改回了几个版本。
ALSO
还
Be sure that your script is returning valid JSON. Use Firebugor Google Chrome's Developer Toolsto check the request's response in the console.
确保您的脚本返回有效的 JSON。使用Firebug或Google Chrome 的开发人员工具在控制台中检查请求的响应。
UPDATE
更新
You will also want to update your code to sanitize the $_POST to avoid sql injection attacks. As well as provide some error catching.
您还需要更新代码以清理 $_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;
}
回答by Peter
Try using jQuery.parseJSON when you get the data back.
取回数据后尝试使用 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);
}
回答by Alnitak
The $.ajax
error
function takes three arguments, not one:
该$.ajax
error
函数接受三个参数,而不是一个:
error: function(xhr, status, thrown)
You need to dump the 2nd and 3rd parameters to find your cause, not the first one.
您需要转储第二个和第三个参数才能找到原因,而不是第一个。
回答by Shahriyar Imanov
In addition to McHerbie's note, try json_encode( $json_arr, JSON_FORCE_OBJECT );
if you are on PHP 5.3...
除了 McHerbie 的说明,json_encode( $json_arr, JSON_FORCE_OBJECT );
如果您使用的是 PHP 5.3 ,请尝试...
回答by Muhammad Saqlain Arif
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>
回答by nishant
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 );
}
});
回答by Tim
Well, it might help someone. I was stupid enough to put var_dump('testing');
in the function I was requesting JSON from to be sure the request was actually received. This obviously also echo's as part for the expected json
response, and with dataType
set to json
defined, the request fails.
嗯,它可能会帮助某人。我愚蠢到把var_dump('testing');
我请求 JSON 的函数放进去,以确保实际收到了请求。这显然也是回声作为预期json
响应的一部分,并且dataType
设置为已json
定义,请求失败。
回答by Ada Bellash Mon Trésor
If you are using a newer version (over 1.3.x) you should learn more about the function parseJSON! I experienced the same problem. Use an old version or change your code
如果您使用的是较新版本(超过 1.3.x),您应该了解有关 parseJSON 函数的更多信息!我遇到了同样的问题。使用旧版本或更改您的代码
success=function(data){
//something like this
jQuery.parseJSON(data)
}