本文介绍: 这句话表示这个参数位置不对,设置header头必须要放到open()后面。应该打开服务器连接,再设置传参格式(下面的传参格式为pplication/xwwwformurlencoded)。xhr.open(“POST”, “https://********”);xhr.setRequestHeader(“Contenttype“, “application/xwwwformurlencoded; charset=utf-8″);xhr.send(‘a=1&b=2′);

1、项目场景

        初学Ajax时,在发送请求设置请求头中的传参格式中,我遇到这样的错误 Failed to executesetRequestHeader’ on ‘XMLHttpRequest’: The objects state must be OPENED


2、问题描述


3、解决方案

这句话表示这个参数位置不对,设置header头必须要放到open()后面。

应该打开服务器连接,再设置传参格式(下面的传参格式为pplication/xwwwformurlencoded)。

    xhr.open(“POST”, “https://********”);

    xhr.setRequestHeader(“Content-type“, “application/x-wwwformurlencoded; charset=utf-8″);

xhr.send(‘a=1&b=2′);

补充:

post方法的第二种传参格式:

// 设置请求头中传参的格式

xhr.setRequestHeader(‘Content-Type’,application/json)

// 将指定参数格式放入到请求

xhr.send( ‘{“a”:1, “b“:2}’ )

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注