![](/img/trans.png)
[英]How to submit attr value and form values with POST using JQuery and PHP?
[英]retrieve PHP post values in submit using jquery
我想以jquery形式在php中檢索帖子值,以便使用jquery提交表單。 我正在使用jquery.submit()函數提交表單。 例子如下
$('#form').submit(function{
var data = '//post variables from php script here';
$.ajax({
type:'post',
data:data,
url://url to save the data,
success:function(response){
//success message here;
}
});
誰能幫幫我嗎?
我不知道您到底想做什么,但據我所知,您似乎需要json_encode php函數。
var data = '<?php echo json_encode($_POST)?>';
您無法直接在JavaScript中提取POST變量-可以使用GET進行提取,因為它們是URL的一部分(?my_get_variable = is_here等)。
如果您確實需要訪問JavaScript中的POST變量,則可以做的是使一些PHP迭代並打印出Post變量。 以下代碼使用傳遞到您頁面的post變量填充了一個名為PostVariables的JavaScript數組:
<script type="text/javascript">
var postVariables = new Array();
<?php foreach($_POST as $key => $value): ?>
postVariables['<?=$key?>'] = '<?=$value?>';
<?php endforeach; ?>
</script>
如果您的POST正文為name = John&pet = Cat&friends = Many,您將獲得以下代碼:
<script type="text/javascript">
var postVariables = new Array();
postVariables['name'] = 'John';
postVariables['pet'] = 'Cat';
postVariables['friends'] = 'Many';
</script>
當然,這確實需要PHP。
如果您需要這種格式的數據,只需修改腳本即可:
<script type="text/javascript">
var myData = "";
<?php foreach($_POST as $key => $value): ?>
myData += "<?=$key?>=<?=$value?>&";
<?php endforeach; ?>
</script>
您可以使用serialize
發布表單數據。 范例表格:
<form id="myForm" method="POST">
<input name="one" value="11" />
<input name="two" value="22" />
<input id="submit" type="submit" value="11" />
</form>
<div id="test"></div>
Java腳本
<script type="text/javascript">
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
data: $("#myForm").serialize(),
url:'mypage.php',
success:function(response){
$("#test").html(response);
}
});
});
</script>
mypage.php
<?php var_dump($_POST); ?>
array (size=2)
'one' => string '11' (length=2)
'two' => string '22' (length=2)
解決了自己。 一直在我的網站上使用插件jquery表單。 使用相同的格式實施表單提交。 http://malsup.com/jquery/form/#ajaxForm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.