XMLHttpRequest() 请求 返回结果JSON 对象与JSON 字符串处理

好久没有看JavaWEB项目了突然拿起来,而且是原生的项目,中JSON 字符串的处理

  1.   json.stingfy() 将对象,数组转换为字符串,json.parse() 将字符串转成json 对象
  •  JSON.stringify(数组或者对象) 
  • JSON.parse(字符串)

     详细用法请参考: https://www.cnblogs.com/panmy/p/5925986.html

     2.  XMLHttpRequest() 请求样例:

 var xhr = new XMLHttpRequest();
          xhr.open("post","../controllerpath", true);
		  //如果在open 方法中指明是post请求 在send提交之前需要设置Http头设置post格式需要指定
          xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
          xhr.onreadystatechange = function() {//Call a function when the state changes.
              if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {//xhr.readyState == 4等价于XMLHttpRequest.DONE
                  // 请求结束后,在此处写处理代码
                  //alert(xhr.responseText);
              
            	  var responseText = xhr.responseText;//返回结果
            	  
            	  var obj = JSON.parse(responseText); 
            	  if(obj['FLAG']=='SUCCESS'){
  	    	    	 var data = obj['rest'];
  	    	    	 alert(JSON.stringify(data));
  	    	    	 initField(data)
  	    	    	}
            	  
              }
          }
          xhr.send("参数1="+参数值1变量+"&参数2="+参数值2变量+"&参数3="+参数值3变量);

参考:https://www.cnblogs.com/panmy/p/5925986.html

猜你喜欢

转载自blog.csdn.net/JHON07/article/details/83475515