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

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

最佳答案

您没有在click函数中调用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>


应该管用

07-24 09:44
查看更多