1

HTML --

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Field: <span id="test"></span>

<form id="form" method="post">
  <input type="submit" name="submit" value="Submit" />
  <input type="submit" name="submit" value="Don't Click" />
</form>

<script>
/* attach a submit handler to the form */
$("#form").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* set all the vars you want to post on here */
  var parameters = { 
    'submit': $('input[name="submit"]').val()
  };

    $.ajax({
         url: 'php/test.php',
         method:'POST',
         data: parameters,
         success: function(msg) {
            $('#test').append(msg);
         }
    })

});

php --

<?php
    $submit = $_POST['submit'];

    if($submit === "Submit"){
        echo 'Success!';
    } else if($submit === "Don't Click") {
        echo 'You Effed Up!';
    }
?>

当我运行 Ajax 调用时,它总是在 Field: 区域中显示 Success。这是为什么?它不应该获取单击的提交按钮的值吗?

4

1 回答 1

2

您需要使用 ajax 调用发送参数:

var parameters = { 
          'submit': 'foo',
          'x': '123a',
          'y': '123b',
          'w': '123c'
          };

j(document).ready(

    j.ajax({
         url: 'php/buttonActions.php',
         method:'POST',
         data: parameters,
         success: function() {
             alert('win');
         }
    })
);

在 PHP 端,使用 POST 而不是 REQUEST。

更新:

如果您想在用户单击提交按钮后通过 ajax 发布,那么您需要根据用户键入的内容设置值。例子:

HTML test.html

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

Field: <span id="test"></span>

<form id="form" method="post">
  <input type="text" name="w" value="" />
  <input type="text" name="submit" value="" />
  <input type="submit" value="submit" />
</form>

<script>
/* attach a submit handler to the form */
$("#form").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* set all the vars you want to post on here */
  var parameters = { 
    'w': $('input[name="w"]').val(),
    'submit': $('input[name="submit"]').val()
  };

    $.ajax({
         url: 'test.php',
         method:'POST',
         data: parameters,
         success: function(msg) {
            $('#test').append(msg);
         }
    })

});
</script>

PHP 测试.php

<?php print_r($_POST); ?>
于 2013-05-03T18:28:57.853 回答