gpt4 book ai didi

php - 无法检索通过 AJAX 发送的 formData 来插入新的 WordPress 帖子,PHP 将值视为空白

转载 作者:行者123 更新时间:2023-12-01 04:42:03 24 4
gpt4 key购买 nike

我通过 jQuery.ajax() 发送 formData,但是处理所有这些的 PHP 函数无法正确检索和识别正在发送的数据。我在 stackoverflow 上查了很多问题,也尝试了很多不同的方法,但都无济于事,最后放弃了。

这一切都是在 WORDPRESS 中完成的。

无法使用序列化,因为我也在发送文件,但为了简单起见,我将它们保留在下面。

这是表单的简化版本:

<form id="newForm" method="post" enctype='multipart/form-data'>
<div>
<label>Title</label>
<input name="title" type="text" value=""/>
</div>
<div>
<label>Content</label>
<input name="content" type="text" value=""/>
</div>
<button type="submit" id="submit_button">SUBMIT</button>
</form>

这是 jQuery:

jQuery(document).ready(function(){
$('#newForm').submit(function(e){
e.preventDefault();
var new_data = new FormData($(this)[0]);
$.ajax({
url:ajaxurl,
type: "POST",
data: {
'action': 'upload_function',
new_data //I've tried new_data: new_data
},
cache:false,
processData:false,
dataType: 'json', //tried not sending it as json dataType, still didn't work
success:function(response){
console.log(response);
if(response.success == 1){
alert("Post inserted");
}else{
alert("Post not inserted");
}
},
error:function(){
alert("Ajax request hasn't passed");
}
});
});
});

这是处理帖子插入的 PHP(它被正确调用,我通过在帖子标题和内容中插入静态值进行了检查),为了简单起见,我省略了随机数和其他内容:

function upload_function(){
$json_result=array();
$json_input=$_POST['new_data'];
$post_vars=json_decode($json_input,true);
$submit_post_data = array (
'post_title' => $post_vars['title'],
'post_content' => $post_vars['content'],
'post_status' => 'draft'
);
$post_id = wp_insert_post($submit_post_data);
if($post_id){
$json_result['success']=1;
}else{
$json_result['success']=0;
}
wp_send_json($json_result);
exit();
}
add_action('wp_ajax_upload_function','upload_function');

最佳答案

您需要序列化表单数据,然后将其传递给 php 代码。对您的 var new_data 赋值执行此操作。

var new_data = $(this).serialize()

编辑1:正如您所说,您有文件需要使用 FormData 对象将文件传递到 ajax 中的服务器。引用下面的代码。

var $element = $(this);
var formdata = new FormData();
var totalFiles = $element.files.length;

if (totalFiles > 0) {
for (var i = 0; i < totalFiles; i++) {
var file = $element.files[i];

formdata.append("FileUpload", file);
}

$.ajax({
type: "POST",
url: Url,
data: formdata,
contentType: false,
processData: false,
success: function (result) {
// make the server return a array of file names that has been saved.
//Post your other form elements data a this point with the filename array.
},
error: function (error) {
console.log("File Upload Failure");
}
});
}

关于php - 无法检索通过 AJAX 发送的 formData 来插入新的 WordPress 帖子,PHP 将值视为空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35639577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com