[英]Using jQuery .serialize() within ajax array to pass the PHP $_POST as Variables?
這是我用來將表單詳細信息發送到php函數的jQuery代碼:
jQuery(document).ready(function($) {
jQuery('.submit').click(function(){
var str = $("#ajaxForms").serialize();
var data = {
action: 'myajax-submit',
serialize: str,
beforeSend: function(){
alert('Sending...');
}
};
jQuery.post(MyAjax.ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
return false;
});
});
這是php函數:
function myajax_submit() {
$whatever = $_POST['serialize'];
echo $whatever;
die();
}
一切正常,但是當出現警告框時,文本會顯示我的html表單#ajaxForms
。 我相信這是因為php函數回顯了$_POST['serialize']
。
在我的表格中,我有一個輸入框,如:
<input id="postID" name="postID" value="First Name" type="text" />
但是當我嘗試回顯php中的$_POST['postID']
變量時,它不會在警告框中顯示任何內容。
我想通過將表格數據序列化發送到php函數,我可以使用與表單輸入相關聯的$ _POST變量嗎?
幫助贊賞。 :)
通過使用jQuery的序列化序列化表單輸入,您可以創建一個字符串,如:
a=1&b=2&c=3&d=4&e=5&postID=10
為了獲得postId,你需要反序列化$ _POST ['serialize']。 為此,您應該執行以下操作:
parse_str($_POST['serialize'], $whatever);
現在, $whatever['postID']
你在尋找$whatever['postID']
。
編輯:修復parse_str():)
你以錯誤的方式實現$.post
。 .serialize()
返回一個字符串。 因此,當您將serialize: str
傳遞給$.post()
,表單本身不再被添加,而是包含序列化表單的純字符串。
下面的代碼是正確的,使用$.ajax
(參見注釋行)。
jQuery('.submit').click(function(){
var str = $("#ajaxForms").serialize();
// If you realllly. want a parameter serialize, uncomment the following line
// str += '&serialize=' + encodeURIComponent(str);
str += '&action=myajax-submit';
jQuery.ajax(MyAjax.ajaxurl, {
method: 'POST',
data: str,
success: function(response) {
alert('Got this from the server: ' + response);
},
beforeSend: function(){
alert('Sending...');
}
});
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.