![](/img/trans.png)
[英]Getting response from Using dataType script with jQuery on ajax request
[英]jQuery $.ajax request of dataType json will not retrieve data from PHP script
我一直在尋找解決方案,但我找不到任何有效的方法。 我試圖從數據庫中獲取一堆數據,然后通過表單中的AJAX自動完成輸入字段。 為此,我決定使用json,因為為什么不呢,對吧? 另外,我一直在考慮發回一個分隔的字符串,然后將它標記出來,在后視中它會更容易並且讓我免於頭疼......因為我已經決定使用json,我想我應該堅持下去,找出問題所在! 發生的事情是,當執行get_member_function()時,警報對話框中會彈出一個錯誤,並顯示“[object Object]”。 我也嘗試過使用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 );
}
我想我知道這個......
嘗試使用PHP的header()函數將JSON作為JSON發送:
/**
* Send as JSON
*/
header("Content-Type: application/json", true);
雖然你傳遞的是有效的JSON,但jQuery的$ .ajax並不這么認為,因為它缺少標題。
jQuery曾經很好沒有標題,但它改回了幾個版本。
也
確保您的腳本返回有效的JSON。 使用Firebug或Google Chrome的開發人員工具在控制台中檢查請求的響應。
UPDATE
您還需要更新代碼以清理$ _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;
}
在獲取數據時嘗試使用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);
}
$.ajax
error
函數有三個參數,而不是一個:
error: function(xhr, status, thrown)
你需要轉儲第二個和第三個參數來找到你的原因,而不是第一個。
除了McHerbie的注釋,請嘗試json_encode( $json_arr, JSON_FORCE_OBJECT );
如果您使用的是PHP 5.3 ...
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>
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 );
}
});
好吧,它可能對某人有所幫助。 我很愚蠢地把var_dump('testing');
在我請求JSON的函數中,以確保實際收到請求。 這顯然也是echo作為預期的json
響應的一部分,並且dataType
設置為json
定義,請求失敗。
如果您使用的是較新版本(超過1.3.x),您應該了解有關函數parseJSON的更多信息! 我遇到了同樣的問題。 使用舊版本或更改代碼
success=function(data){
//something like this
jQuery.parseJSON(data)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.