2012-08-04 118 views
0

我有一個帶有onkeyup事件的窗體。 我嘗試發送一個變量給我的PHP腳本,並在div中顯示結果。

感謝這個論壇上,我得到了我的測試功能,一半的工作:

jQuery.post(the_ajax_script.ajaxurl, 

如果我繼續: 1)jQuery("#theForm").serialize(), 我得到響應文本是「Hello World」的 如果我試圖通過一個變量: 2){ name: "p" }, 我得到:-1

的JavaScript

function submit_me(){ 
jQuery.post(
    the_ajax_script.ajaxurl, 
    { name: "p" }, 
function(response_from_the_action_function){ 
    jQuery("#txtHint").html(response_from_the_action_function); 
    } 
); 
} 

PHP

<?php 
function the_action_function(){ 
$name = $_POST['name']; 
echo "Hello World, " . $name; 
die(); 
} 
?> 

FORM

<form id="theForm"> 
<input type="text" name="user"> 
<input name="action" type="hidden" value="the_ajax_hook"> 
<input id="submit_button" value = "Click This" type="button" onkeyup="submit_me()"> 
<form> 

其實我是想onkeyup="submit_me(this.value, 0)" 我通過自己的管理-ajax.php文件一個WordPress這樣做。

問題在哪裏?

編輯

顯然,我不得不添加行動數據

{ action:'the_ajax_hook', name:"p" } 

我猜它WP的要求,而不是jQuery的,因爲我看到的例子是這樣的:

$.post("test.php", { name: "John", time: "2pm" } 

無處不在。

+0

爲什麼你死()在你的PHP腳本的結束? – jrubins 2012-08-04 19:04:27

+0

另外,你不需要PHP代碼中的函數。 PHP腳本運行時可能不會被調用。 – jrubins 2012-08-04 19:05:36

回答

0

像這樣的東西應該工作:

<html> 
    <head> 
     <script> 
      $(document).ready(function() { 
       $("#my_form").submit(function(event) { 
        event.preventDefault() // to prevent natural form submit action 
        $.post(
         "processing.php", 
         { name: "p" }, 
         function(data) { 
          var response = jQuery.parseJSON(data); 
          $("#txtHint").html(response.hello_world); 
         } 
        ); 
       }); 
      }); 
     </script> 
    </head> 
    <body> 
     <form id="my_form" action="/" method="post"> 
      <input type="text" name="user" /> 
      <input name="action" type="hidden" value="the_ajax_hook" /> 
      <input type="button" name="submit" value = "Click This" /> 
     </form> 
     <div id="txtHint"></div> 
    </body> 
</html> 

然後在processing.php:

<?php 
    $name = $_POST['name']; 
    $response['hello_world'] = "Hello World, " . $name; 
    echo json_encode($response); 
?>