通过Jquery AJAX传递PHP变量

Dan*_*l H 4 php variables ajax jquery

我正在尝试学习Jquery AJAX函数,但我正在努力研究如何将PHP变量传递到我的主文档中.

这就是我目前拥有的:

<script>
  var refreshId = setInterval(function() {
    $.ajax({
      url: "test.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
        $('#testdiv').html(data.test1);
        $('#testdiv').append(html(data.test2));
        //parse the json data
      }
    });

}, 1000);
</script>
Run Code Online (Sandbox Code Playgroud)

San*_*kha 5

您应该使用jsonxml格式化并解析它,并获取变量.

<script src="jquery.js"></script>
<script>
    $.ajax({
      url: "test.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
        alert(data.test1);
        //parse the json data
      }
    });
</script>
Run Code Online (Sandbox Code Playgroud)

test.php

<?php

$test = array();
$test['test1'] = '1';
$test['test2'] = '2';
$test['test3'] = '3';

echo json_encode($test);
//echo nothing after this //not even html
Run Code Online (Sandbox Code Playgroud)