zoukankan      html  css  js  c++  java
  • 使用jQuery发送POST,Ajax请求返回JSON格式数据

    问题:
    使用jQuery POST提交数据到PHP文件, PHP返回的json_encode后的数组数据,但jQuery接收到的数据不能解析为JSON对象,而是字符串{"code":-1,"msg":"123","data":[]}

    jQuery get() 和 post() 方法用于通过 HTTP GET 或 POST 请求从服务器请求数据。

    jQuery $.get() 方法
    $.get() 方法通过 HTTP GET 请求从服务器上请求数据,在URL地址上可以看到传递的参数,一般用于传递少量数据。
    语法: $.get(URL,callback);
    详细语法:$(selector).get(url, data, success(response,status,xhr),dataType)

    jQuery $.post() 方法
    $.post() 方法通过 HTTP POST 请求从服务器上请求数据,在URL地址上不可以看到传递的参数,一般用于传递大量数据。
    语法:$.post(URL,data,callback);
    详细语法: jQuery.post(url,data,success(data, textStatus,jqXHR),dataType)

    查看$.post()详细的语法:
    jQuery.post(url,data,success(data, textStatus,jqXHR),dataType)
    你会发现,最后边有个参数 dataType,这个就是问题所在。
    这个dataType是可选参数,它规定预期的服务器响应的数据类型。默认执行智能判断(xml、json、script 或html)。

    详细说明
    该函数是简写的 Ajax 函数,等价于:
    $.ajax({
      type: 'POST',
      url: url,
      data: data,
      success: success,
      dataType: dataType
    });

    解决:

    $.post() 加上最后边的一个可选参数 dataType 为“json”类型


    示例:获得 test.php 页面返回的 json 格式的内容:
    $.post("test.php", { "func": "getNameAndTime" },
       function(data){
        alert(data.name); // John
        console.log(data.time); // 2pm
       },"json");

    示例:获得 test.php 页面的内容,并存储为 XMLHttpResponse 对象,并通过 process() 这个JavaScript 函数进行处理:
    $.post("test.php", { name: "John", time: "2pm" },
       function(data){
        process(data);
       },"xml");

    Struts2中对于后台向前端返回JSON格式数据一般使用以下方式:
    <span style="font-size:18px;">	public void writeJson2Resp(String json) throws IOException {
    		HttpServletResponse resp = ServletActionContext.getResponse();
    		resp.setCharacterEncoding("gbk");
    		resp.setContentType("text/html;charset=gbk");  //这一句没加入会导致乱码
    		PrintWriter out = resp.getWriter();
    		out.write(json);
    		out.flush();
    		out.close();
    	}</span>

    在 BaseAction 实现该方法,那么其他的 Action  只要继承了改类,就可以使用该方法向前台页面返回JSON格式数据

    参考链接:
    jQuery ajax 参考手册
    http://www.w3school.com.cn/jquery/jquery_ref_ajax.asp

    HTTP 方法:GET 对比 POST
    http://www.w3school.com.cn/tags/html_ref_httpmethods.asp

    jQuery ajax - post() 方法:
    http://www.w3school.com.cn/jquery/ajax_post.asp

    jQuery ajax - get() 方法
    http://www.w3school.com.cn/jquery/ajax_get.asp

    关注公众号,分享干货,讨论技术


  • 相关阅读:
    BZOJ 1002 轮状病毒
    poj_1952最大下降子序列,统计个数
    poj_3468线段树成段更新求区间和
    hdu_4707
    uva_644暴力加字典树解法
    正则表达式:处理文本内容中特定的字符串
    grep:文本搜索工具
    分析文本的工具:wc,sort,uniq,diff和patch
    按列抽取文本cut和合并文件paste
    显示文本前或后行内容:head,tail
  • 原文地址:https://www.cnblogs.com/molashaonian/p/9097617.html
Copyright © 2011-2022 走看看