从 ajax 调用中检索 php 变量,但不起作用



当我使用此代码时,什么都没有发生并调用ajax时,我正在查看一些在线论坛,说我需要使用json编码通过ajax传递变量,但它只是在网页顶部回显它。

阿贾克斯测试

    <html>
    <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
    $("#test").click(function(){
        $.ajax({
            event.preventDefault(),
            url:'ajaxUser.php',
            type:'POST',
            dataType: 'json',
            success:function(data){
                alert(data.id);
            }
        )};
    });
    </script>
    </head>
  <body>
    <form method="post">
      <input name="userName">
      <input name="submit" type="button" value="Submit" id="test">
    </form>
  </body>
</html>

ajaxUser

    <?php
    echo json_encode(array('id' => 123, 'messageid' => "test"));
    ?>

您没有在单击函数中调用event参数。不要在ajax函数中调用preventDefault(),如果你想在头元素中编写,你还需要在document.ready()内编写你的js!

   <html>
    <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>       
    </head>
  <body>
    <form method="post">
      <input name="userName">
      <input name="submit" type="button" value="Submit" id="test">
    </form>
    <script>
    $("#test").click(function(event){
        event.preventDefault();
        $.ajax({
            url:'ajaxUser.php',
            type:'POST',
            dataType: 'json',
            success:function(data){
                alert(data.id);
            }
        });
    });
    </script>
  </body>
</html>

应该工作

php 代码需要位于名为 AjaxTesting.php 的不同文件中,并且您永远不会在 javascript 中调用函数post()。所以我们可以在表单提交事件处理程序中调用它

尝试添加:

$(function(){
   $('form').submit(function(event){
       event.preventDefault()
       post();
   })
});

另请注意,html 页面需要在同一台服务器上运行,而不是从本地文件运行,ajax 才能工作

最新更新