php - 通过 Jquery AJAX 传递 PHP 变量

标签 php jquery ajax variables

我正在尝试学习 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>

最佳答案

你应该使用json或者xml格式解析,得到变量。

<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>

关于 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

关于php - 通过 Jquery AJAX 传递 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5700122/

相关文章:

php - 获取 div 值的最佳方法是什么?

php - 将客户电子邮件地址添加到 WooCommerce 中的新帐户电子邮件通知

php - 如何在 Linux 中使用 C 编程检查我的 php 和 pear 版本?

jquery - 谷歌浏览器在 Windows 上插入框阴影错误,而不是在 Mac 上 : Better workaround?

jquery - metronic portlet 通过外部按钮扩展

javascript - Tinybox 不运行 (eval) javascript 代码

ajax - CasperJS 无法抓取 AJAX 网页

php - 在 PHP 中,当订购多个商品时,如何将这些商品的数量减 1?

javascript - 如何在javascript中将菜单转换为多维关联数组?

ruby-on-rails - Rails复选框AJAX调用,不想呈现任何内容