【问题标题】:In response jsonp is overwriting the first value with the second value作为响应,jsonp 正在用第二个值覆盖第一个值
【发布时间】:2014-08-05 10:44:30
【问题描述】:

这是我的 jsonp 代码,我在其中从在线服务器获取数据,并希望在我的 2 个 div 中显示,即标题和描述。但是代码正在用 ajax_reponse 加载的最后一个内容替换我的第一个 div。

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);
}

这是我的 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).")";


?>

【问题讨论】:

  • 使用appendChild()方法代替innerHTML

标签: javascript php ajax json jsonp


【解决方案1】:

这样做是有道理的,因为您的代码告诉它:

document.getElementById("first").innerHTML=data[key];

你的 for 应该是 for each:

for each(var key in data) {
    document.getElementById("first").innerHTML=data[key];
}

您的代码表示将 innerHTML 替换为您从服务器获得的值。

如果您的投诉是响应是 LAST 响应,那么服务器正在缓存您的请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 2014-01-12
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多