简体   繁体   English

将参数从Ajax传递到PHP文件

[英]Pass parameter from Ajax to PHP file

I call a PHP file from AJAX and I want to pass also a variable. 我从AJAX调用了一个PHP文件,我还想传递一个变量。 This is my code: 这是我的代码:

echo "<h4 style='color:white'>Messages</h4>";
echo "<textarea cols='50' rows='10' style='font-size: 24px;'></textarea><br><br>";
echo "<button id='sendmessage' style='padding:10px'>Submit</button>";
echo "<button id='deletemessage' style='margin-left:5px;padding:10px'>Delete</button>";


echo "<script>
    jQuery('#sendmessage').click(function(){
        jQuery.ajax({
            data: { content: jQuery('textarea').val() },
            url:'wp-content/themes/dt-chocolate/postmessages.php',
            success:function(data){}
        });
    });
    </script>"

and the PHP file: 和PHP文件:

<?php
require_once('/opt/lampp/htdocs/mydomain/wp-config.php');

$post = array(
        'post_content'   =>  data.content,
        'post_title'     =>  "testing",
        'post_status'    =>  'publish',
        'post_type'      =>  'post',
        'post_category'  =>  array(28)  // Default empty.
    );  



wp_insert_post( $post );
?>

However, the content of the post is "datacontent" and not the actual text from the textarea. 但是,帖子的内容是“ datacontent”,而不是来自文本区域的实际文本。 What am I doing wrong? 我究竟做错了什么?

echo "<script>
jQuery('#sendmessage').click(function(){
    jQuery.ajax({
        data: { content: jQuery('textarea').val() },
        url:'wp-content/themes/dt-chocolate/postmessages.php',
        type: 'POST',
        success:function(data){}
    });
});
</script>";

- --

$post = array(
    'post_content'   =>  $_POST['content'],
    'post_title'     =>  "testing",
    'post_status'    =>  'publish',
    'post_type'      =>  'post',
    'post_category'  =>  array(28)  // Default empty.
);  

Set .ajax type (method) to 'POST' , then you can read POST request variables in PHP from the $_POST array. .ajax type (方法)设置为'POST' ,则可以从$_POST数组中读取PHP中的POST请求变量。

First, you'd probably want to use POST instead of GET. 首先,您可能想使用POST而不是GET。 Just add type: 'POST' to the ajax params or use the "post()" function. 只需在ajax参数中添加类型:“ POST”或使用“ post()”函数即可。

On the server side, the way the value should be retrieved is by using the $_GET (or $_POST) global variables. 在服务器端,应使用$ _GET(或$ _POST)全局变量来检索值。 Your content should be in $_GET['content']. 您的内容应在$ _GET ['content']中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM