zoukankan      html  css  js  c++  java
  • JQuery ajax 调用webservice妙用


    jQuery的ajax调用很方便,传参的时候喜欢用Json的数据格式。比如:

    JavaScript代码,增加一个评论
    function AddComment(content) {
        var threadId = $("#span_thread_id").html();
        var groupId = $("#span_group_id").html();
        var groupType = $("#span_group_type").html();
        var title = $("#thread_title").html();
        var content = content.replace(/\x22/g,'"');
        $.ajax({
            url: '/WebService/GroupService.asmx/AddThreadComment',
            data: '{threadId:' + threadId + ',groupId:' + groupId + ',groupType:' + groupType + ',title:"' + title + '",content:"' + content + '"}',        type: 'post',
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            cache: false,
            success: function(data) {
                //根据返回值data.d判断是不是成功
            },
            error: function(xhr) {
                //中间发生异常,查看xhr.responseText
            }
        });
    }

    这中间最麻烦,最容易出错的也是拼接Json字符串,字符型参数的值要添加引号,而且对于用户输入的文本字段要对',/等进行特殊处理

    意外的机会,上司给我推荐了一种新的方法,看下面代码:

    JavaScript代码,巧用JSON传参数
    function AddComment(content) {
        var comment = {};
        comment.threadId = $("#span_thread_id").html();
        comment.groupId = $("#span_group_id").html();
        comment.groupType = $("#span_group_type").html();
        comment.title = $("#thread_title").html();
        comment.content = content;
        $.ajax({
            url: '/WebService/GroupService.asmx/AddThreadComment',
            data: $.toJSON(comment),
            type: 'post',
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            cache: false,
            success: function(data) {
                //根据返回值data.d处理   
            },
            error: function(xhr) {
                //中间发生异常,具体查看xhr.responseText
            }
        });
    }

    直接用$.toJSON(对象)即可;
    jQuery的JSON插件:http://code.google.com/p/jquery-json/
     
    另外参考:
     
     
  • 相关阅读:
    【转载】ARM与单片机的区别
    关于头文件定义的一点思考
    关于*** WARNING L15: MULTIPLE CALL TO SEGMENT
    【转】单片机中volatile定义的作用详解
    关于单片机位数的思考(8位、16位、32位)
    memcpy函数
    ubuntu下打开windows里的txt文件乱码解决
    linux source filename
    linux环境设置export
    pdf转word工具
  • 原文地址:https://www.cnblogs.com/userbibi/p/3003820.html
Copyright © 2011-2022 走看看