Javascript 作为响应,jsonp用第二个值覆盖第一个值
这是我的jsonp代码,其中我从在线服务器获取数据,并希望在我的2个div中显示,即title和description。但是代码正在用ajax\u Response加载的最后一个内容替换我的第一个divJavascript 作为响应,jsonp用第二个值覆盖第一个值,javascript,php,ajax,json,jsonp,Javascript,Php,Ajax,Json,Jsonp,这是我的jsonp代码,其中我从在线服务器获取数据,并希望在我的2个div中显示,即title和description。但是代码正在用ajax\u Response加载的最后一个内容替换我的第一个div function ajax_request() { jsonp("http://example.com/jSonApi/json_data.php", "ajax_response"); } /**Response (Called when data has been r
function ajax_request() {
jsonp("http://example.com/jSonApi/json_data.php",
"ajax_response");
}
/**Response (Called when data has been retrieved)
*
* @param object data Javascript (JSON) data object received
* through <script> request
*/
function ajax_response(data) {
for(var key in data) {
document.getElementById("first").innerHTML=data[key];
}
}
function jsonp(url, callback)
{
if (url.indexOf("?") > -1) {
url += "&jsonp=";
}
else {
url += "?jsonp=";
}
url += callback + "&";
url += new Date().getTime().toString(); // prevent caching
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
document.getElementsByTagName('head')[0].appendChild(script);
}
函数ajax\u request(){
jsonp(“http://example.com/jSonApi/json_data.php",
“ajax_回应”);
}
/**响应(检索数据时调用)
*
*@param object data接收到Javascript(JSON)数据对象
*通过请求
*/
函数ajax\u响应(数据){
for(var输入数据){
document.getElementById(“first”).innerHTML=data[key];
}
}
函数jsonp(url,回调)
{
if(url.indexOf(“?”>-1){
url+=“&jsonp=”;
}
否则{
url+=“?jsonp=”;
}
url+=回调+“&”;
url+=新日期().getTime().toString();//防止缓存
var script=document.createElement(“脚本”);
setAttribute(“src”,url);
setAttribute(“type”、“text/javascript”);
document.getElementsByTagName('head')[0].appendChild(脚本);
}
这是我的PHP代码
<?php
// Connection to the database
include("connection.php");
$startQuery = mysql_query("select * from image_gallery where recid=474") or die (mysql_error());
if (mysql_num_rows($startQuery)>0){
$rs=mysql_fetch_array($startQuery);
$title = $rs["gallerytitle_en"];
$descp =trim(preg_replace('/\s\s+/', ' ', $rs["gallerydescp_en"]));
$jsonData=array("data_1" => $title , "data_2" => $descp);
}
mysql_free_result($startQuery);
echo $_REQUEST["jsonp"]."(".json_encode($jsonData).")";
?>
这样做是有道理的,因为您的代码告诉它:
document.getElementById("first").innerHTML=data[key];
您的for应为a for each:
for each(var key in data) {
document.getElementById("first").innerHTML=data[key];
}
您的代码显示将innerHTML
替换为从服务器获得的值
如果您的投诉是响应是最后一个响应,则服务器正在缓存您的请求。使用appendChild()
方法,而不是innerHTML