我试图通过ajax和表单数据方法获取已选择上传的文件的名称。我目前在WordPress工作,下面是我的代码。我希望通过该函数返回所选文件的名称。 Null在$_FILES
中返回,也请我如何上传此文件,但第一个障碍是我的$_FILES['file']
始终为null
。感谢
Html上传表单
[testupload]
<form id="test" action="" method="post" enctype='multipart/form-data'>
<input id="files" type="file" name="file" style="margin-top:12px;">
<input name="testupload" type="submit" value="upload"/>
</form>
<div id="result"></div>
Ajax代码
jQuery(function ($) {
$("#test").submit(function (e) { //form is intercepted
e.preventDefault();
var sent = $(this).serializeArray();
var sentdata = $(this).serializeArray();
//$("#result").html("zeeshan aslam durrani");
alert("jquery file is connected");
//serialize the form which contains secretcode
var file = jQuery(document).find('input[type="file"]');
formData = new FormData();
var image = $('#files')[0].files[0];
formData.append("file",image);
alert(formData)
//Add the additional param to the data
sent.push({
name: 'action',
value: 'testfunction',
data: formData
})
//set sentdata as the data to be sent
$.post(yes.ajaxurl, sent, function (res) { //start of funciton
//$("#myresult").append(res.l);
$("#result").html("");
$("#result").html(res);
alert(res);
//$.parseJSON(data);
return false;
} //end of function
,
'json'); //set the dataType as json, so you will get the parsed data in the callback
}); // submit end here
});
PHP代码
//test upload
add_action( 'wp_ajax_testfunction', 'testfunction' );
add_action( 'wp_ajax_nopriv_testfunction', 'testfunction');
add_shortcode('testupload','testupload');
function testupload()
{
// register & enqueue a javascript file called globals.js
wp_register_script( 'testscript', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) );
wp_enqueue_script( 'testscript');
// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'testscript', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function testfunction()
{
//echo json_encode("My name is khan");
echo json_encode($_FILES['file']);
die();
}
null
中始终返回$_FILES
...请帮助和谢谢