doushang2023 2014-06-15 12:33
浏览 37

作为响应,jsonp用第二个值覆盖第一个值

This is my jsonp code in which i am getting the data from online server and want to show in my 2 divs which is title and description. But the code is replacing my first div with the last content loaded by ajax_reponse.

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

This is my PHP code

<?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).")";


?>
  • 写回答

1条回答 默认 最新

  • dpr26232 2014-06-15 12:38
    关注

    It makes sense that's it doing that because your code is telling it to:

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

    Your for should be a for each:

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

    Your code says replace the innerHTML with the value you got from the server.

    If your complaint is that the response is the LAST response then your request is being cached by the server.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起