从ajax调用中检索php变量但不能正常工作

时间:2017-01-16 04:59:10

标签: javascript php jquery ajax

当我使用这个代码什么都没有,并调用ajax没有任何反应,我正在看一些在线论坛说我需要使用json编码通过ajax传递变量,但它只是在网页的顶部回声。

AjaxTesting

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

2 个答案:

答案 0 :(得分:1)

您没有在点击功能中调用event参数。不要在ajax函数中调用preventDefault(),如果你想在header元素中写,你还需要在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>

应该工作

答案 1 :(得分:0)

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

中调用它

尝试添加:

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

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