将参数从 Ajax 传递到 PHP 文件
Pass parameter from Ajax to PHP file
我从 AJAX 调用了一个 PHP 文件,我还想传递一个变量。这是我的代码:
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>"
和 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 );
?>
但是,post 的内容是 "datacontent" 而不是文本区域中的实际文本。我做错了什么?
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.
);
将.ajax
type
(方法)设置为'POST'
,则可以从$_POST
中读取PHP中的POST请求变量数组。
首先,您可能希望使用 POST 而不是 GET。只需将 type: 'POST' 添加到 ajax 参数或使用 "post()" 函数。
在服务器端,检索值的方法是使用 $_GET(或 $_POST)全局变量。您的内容应该在 $_GET['content'].
我从 AJAX 调用了一个 PHP 文件,我还想传递一个变量。这是我的代码:
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>"
和 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 );
?>
但是,post 的内容是 "datacontent" 而不是文本区域中的实际文本。我做错了什么?
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.
);
将.ajax
type
(方法)设置为'POST'
,则可以从$_POST
中读取PHP中的POST请求变量数组。
首先,您可能希望使用 POST 而不是 GET。只需将 type: 'POST' 添加到 ajax 参数或使用 "post()" 函数。
在服务器端,检索值的方法是使用 $_GET(或 $_POST)全局变量。您的内容应该在 $_GET['content'].