簡體   English   中英

jQuery post無法在php中獲得$ _POST

[英]jQuery post cannot get $_POST in php

我有一個帶有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 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)"我正在通過他們的admin-ajax.php文件在WordPress上執行此操作。

問題出在哪里?

編輯

顯然我必須對數據添加操作

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

我猜想它的WP要求,而不是jQuery,因為我看到了這樣的示例:

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

到處。

這樣的事情應該起作用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM