js如何提交post使php获取(使用原生js)

JavaScript016

js如何提交post使php获取(使用原生js),第1张

document.querySelector("#btnAjax").onclick = function () {

        var ajax = new XMLHttpRequest()

        // 使用post请求

        ajax.open('post','ajax_post.php')

        // 如果 使用post发送数据 必须 设置 如下内容

        // 修改了 发送给 服务器的 请求报文的 内容

        // 如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:

        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded")

        // 发送

        // post请求 发送的数据 写在 send方法中

        // 格式 name=jack&age=18 字符串的格式

        ajax.send('name=jack&age=998')

        // 注册事件

        ajax.onreadystatechange = function () {

            if (ajax.readyState==4&&ajax.status==200) {

                console.log(ajax.responseText)

            }

        }

    }

使用ajax

                $.ajax({

"type" : 'get',

"url" : "访问后台路径",

"dataType" : "json",

"data" : {

    name:"传给后台的参数"

},

"success" : function(resp) {

//返回成功信息-----》resp

},

"error":function(emsg){

//返回失败信息-----》emsg

}

})

$.ajax({

url:"(你要请求的url地址)",

data:{

"key1" : "value1",

"key2" : "value2"

},

type:"post", //此处传递方式可以是get也可以是post

dataType:"json", //后台要返回的数据形式

success:function(data){//请求成功的要执行的回调函数

console.log('请求成功')

console.log(data)

},

error:function(msg){//请求失败的要执行的回调函数

console.log('请求失败')

console.log(msg)

}

})