我有一些基本信息的表单元素,提交如何使用jquery将表单值发布为json格式?
如何成功测试其发布内容?
HTML:
<table>
<tr>
<td>first name</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>last name</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>mobile</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>address</td>
<td><textarea></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="button" value="Submit" /></td>
</tr>
</table>
答案 0 :(得分:1)
使用$.post()执行此任务:
$("myForm").submit(function(event) {
/* preventing the submit */
event.preventDefault();
var myArray = [];
/*
using myArray.push(value);
you can add all the value of yours textboxes to this array.
*/
var myJsonArray = JSON.parse(myArray);
$.post("path_to_my_php_file/myfile.php", { json_array : myJsonArray }, function(result) {
/* this function can eventualy used to process the result of your php */
});
});
如果您的表单使用GET
方法发送数据,请使用$.get()函数。
答案 1 :(得分:0)
您可以使用ajax以JSON格式发送表单数据,请查看以下代码:
var myformData = JSON.stringify($("#your-form-id").serializeArray());
$.ajax({
type: "POST",
url: "ServerURL",
data: myformData ,
success: function(){},
dataType: "json",
contentType : "application/json"
});
答案 2 :(得分:0)
<table>
<tr>
<td>first name</td>
<td><input type="text" name="firstname" id="fname"/></td>
</tr>
<tr>
<td>last name</td>
<td><input type="text" nmae="lastname" id="lname" /></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" id="email"/></td>
</tr>
<tr>
<td>mobile</td>
<td><input type="text" id="mobile" /></td>
</tr>
<tr>
<td>address</td>
<td><textarea id="address"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="button" value="Submit" id="buttonClick" /></td>
</tr>
</table>
在Jquery中添加以下代码:
$("#buttonClick").click(function(){
var fname,lname,email,mobile,address;
fname=$("#fname").val();
lname=$("#lname").val();
email=$("#email").val();
mobile=$("#mobile").val();
address=$("#address").val();
$.ajax({
type:"post";
url:"their write your url for php file ";
data:"fname="+fname+"&lname="+lname+"&email="+email+"&mobile="+mobile+"&address="+address;
success:function(res)
{
}
});
});
at url place your php file where you want to post these values you can get these values by using $_POST['fname'] etc.. in your php file