我在使用 json 将变量从 php 传递到 javascript 时遇到问题,基本上问题是在我的 javascript 中我可以调试和查看 responseText 中的项目,但我无法将它们分配给变量或查看它们,我也尝试过单个项目,但没有管理任何关于为什么会发生这种情况的想法。
function ajaxrequestDB() {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest) { // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
}
else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null){ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function() { // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
var url='http://localhost/Scripts/refresh.php';
//var url='http://cpdtest.zzl.org/Scripts/hidemarker.php?Name='+myname;
AJAX.open("GET", url, true); // Open the url this object was set-up with.
AJAX.send(); // Send the request.
alert(AJAX.responseText);
var result = AJAX.responseText;
eval(result);
//alert(result);
}
从上面如果我对 AJAX.responseText 进行调试,我可以从我的 php 文件中看到返回的数据,但是 alert(AJAX.responseText) 我只能看到一个空白的警报窗口。
下面也是我的 php 文件,它从 db 读取并将变量发送到 javascript。
<?php
header('Content-type: application/json');
//$con = mysql_connect("localhost","770132_admin","admin");
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cpd", $con);
$SQL = "SELECT name from markers";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)){
$data[]= $db_field;
}
echo json_encode($data);
?>