简体   繁体   English

jQuery post无法在php中获得$ _POST

[英]jQuery post cannot get $_POST in php

I have a form with an onkeyup event. 我有一个带有onkeyup事件的表单。 I try to send a variable to my php script and show result in a div. 我尝试将变量发送到我的PHP脚本并在div中显示结果。

Thanks to this forum I got my test function to half work: 多亏了这个论坛,我的测试功能才能完成一半:

jQuery.post(the_ajax_script.ajaxurl,

If I continue with: 1) jQuery("#theForm").serialize(), I get response text which is "Hello World" If I try to pass a variable: 2) { name: "p" }, I get: -1 如果继续:1) jQuery("#theForm").serialize(),得到的响应文本是“ Hello World”。如果我尝试传递变量:2) { name: "p" },我得到: -1

JavaScript 的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

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

I actually want onkeyup="submit_me(this.value, 0)" I am doing this on a WordPress through their admin-ajax.php file. 我实际上想要onkeyup="submit_me(this.value, 0)"我正在通过他们的admin-ajax.php文件在WordPress上执行此操作。

Where is the problem in this? 问题出在哪里?

EDIT 编辑

Apparently I had to add action to data 显然我必须对数据添加操作

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

I guess its WP requirement, rather than jQuery, because I saw examples as this: 我猜想它的WP要求,而不是jQuery,因为我看到了这样的示例:

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

everywhere. 到处。

Something like this should work: 这样的事情应该起作用:

<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>

And then in processing.php: 然后在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