Skip to content

JS POST Demo for PHPer

hzlzh edited this page Feb 28, 2013 · 1 revision

此方式适用临时的单方面的对接口,如:后台开发的demo用例制作,方便快速发起提交请求到数据库

POST 接口数据结构

最终raw数据 action=insert&data%5Bitem1%5D=aaa&data%5Bitem2%5D=bbb&data%5Bitem3%5D=ccc&tablename=user

var postdata = {
	"action": "insert",
	"data": {
		"item1":"aaa",
		"item2":"bbb",
		"item3":"ccc"
	},
	"tablename":"user"
};

调用范例

var api = "/ajax/xxxx";

postIt(obj,api,postdata,callback)
// obj 目标按钮 是一个jQuery对象,如 $("#ID")
postIt($('#ID'),"/ajax/xxxx",{"action": "insert","data": {"item1":"aaa","item2":"bbb","item3":"ccc" },"tablename":"user"})

函数原型

// POST

var postIt = function(obj,api,postdata){
	obj.bind('click',function(){
		$.post(api, postdata, function(data){
			console.log(data.success);
		});
	})
}

返回值结构

{
    success : flase
}

范例:

例如HTML表单如下:

<form>
	<input id="formUsername" type="text" name="username">
	<input id="formEmail" type="text" name="email">
	<input id="formSubmit" type="submit" value="Submit">
</form>

#### JS书写应为:$('#formUsername').val()

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
	postIt($('#formSubmit',"/ajax/xxxx",{
		"action": "insert",
		"data": {
			"username":$('#formUsername').val(),
			"email":$('#formUsername').val()
		},
		"tablename":"user"}
		)
</script>