我是PHP / jquery的新手
我想问一下如何使用json格式的ajax从(名称,年龄等)表单字段发送json数据。遗憾的是,我找不到与此相关的任何信息,甚至可以动态地执行此操作? Google搜索仅提供诸如手动建立数据之类的答案。例如:name: X Y
,age: 32
,等等。
反正有这样做吗?
谢谢您的帮助!
编辑:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
最佳答案
这是一个简单的
这是我的test.php仅用于测试
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
这是我的index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
两个文件都放在同一目录中