通过Ajax接收多个数据

时间:2017-02-26 20:31:06

标签: jquery ajax

我需要每次运行一些PHP代码(比方说)2秒并更新一些文本(完整代码中,有来自MySql和其他许多数据的数据)。我决定使用ajax。我需要从Ajax接收多个数据。我试图在堆栈溢出中为这个问题实现几个响应,但可能 - 我没做对。

我尝试实施的一种可能方式是:

html和js:

    <html>
        <head>
            <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
        </head> 
  <body>
    <span id="jmeno1" style="font-weight:bold">aaa</span>:
    <span id="text1" style="font-weight:normal">bbb</span><br>

    <span id="jmeno2" style="font-weight:bold">ccc</span>:
    <span id="text2" style="font-weight:normal">ddd</span><br>

    <span id="jmeno3" style="font-weight:bold">eee</span>:
    <span id="text3" style="font-weight:normal">fff</span><br>
  </body>
    </html>
    <script type="text/javascript">

    setInterval(function() 
      {
      repeating();
      }, 2*1000);

    function repeating()
            {
            txt = "nic";
            $.post("repeating.php", {dd: txt}, function(data)
                {
                var result = $.parseJSON(data);
                $('#jmeno1').val(result.name);
                $('#text1').val(result.credit);
                });
                return false;
            };
    </script>

这是php文件:

<?php
$c_name="test1";
$c_credit="test2";

$data = array(
    'name' => $c_name,
    'credit' => $c_credit,
);
echo json_encode($data);
?>

我试图实施的其他方式,也没有工作在下面。 HTML和js文件是:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
    </head> 

<body>
  <span id="jmeno1" style="font-weight:bold">aaa</span>:
  <span id="text1" style="font-weight:normal">bbb</span><br>

  <span id="jmeno2" style="font-weight:bold">ccc</span>:
  <span id="text2" style="font-weight:normal">ddd</span><br>

  <span id="jmeno3" style="font-weight:bold">eee</span>:
  <span id="text3" style="font-weight:normal">fff</span><br>
</body>

</html>
<script type="text/javascript">

setInterval(function() 
  {
  repeating();
  }, 2*1000);

function repeating()
        {
        txt = "nic";
        $.post("repeating.php", {dd: txt}, function(value)
            {
            var data = value.split(",");
            $("#jmeno1").val(data[0]);
            });
            return false;
        };
</script>

php文件是:

<?php
$one = "test1";
$two = "test2";
echo $one.",".$two;
?>

Acctualy我需要的是通过ajax接收数组(或更好的数组)。我将非常感谢这种解决方案的帮助或建议任何其他解决方案。谢谢 :)。

1 个答案:

答案 0 :(得分:0)

$。不推荐使用parseJSON,请使用JSON.parse

$.post("repeating.php", {dd: txt}, function(value) {
    var data = JSON.parse(value);
    $("#jmeno1").val(data[0]);
});