你的位置:首页 > Java教程

[Java教程]一些ajax代码


 1 $.ajax({ 2       type : "get", 3       url : "list_hot_ajax.json", 4       data : {"provinceId":'${province.provinceId}'}, 5       dataType : "json", 6       success : function(json) { 7          8         if(json.length == 0 || json == null) { 9           $("#hotsearch").remove(); 10           return false; 11         } 12         var hotModule = ""; 13         for ( var i in json) { 14           var word = json[i].hotWord; 15           var isLight = json[i].isLight; 16           var tempClass = "search_blue"; 17           if(isLight == 1) { 18             tempClass = "search_red"; 19           } 20           var index = parseInt(i)+1; 21                  22           //解决ie浏览器不支持jq trim方法 23           String.prototype.trim = function () { 24             return this .replace(/^\s\s*/, '' ).replace(/\s\s*$/, '' ); 25           } 26            27           var hurl ="list?key="+word+"&cityId="+"${city.cityId}"+"&provinceId="+"${province.provinceId}"+"&from=10202&no_re=1&nh=1"; 28           if(json[i].url.trim()!=""){ 29             hurl=json[i].url.trim(); 30           } 31            32          33           hotModule = hotModule + "<li><a class='"+tempClass+"' id='G5_hot_"+index+"' type='"+index+"' href='"+hurl+"'>"+ 34                         word + 35                       "</a></li>"; 36                        37         } 38         $("#hotsearch").append(hotModule); 39       } 40     }); 41 ------------------------------------------------------------------------------------------------------------------------------------------------------------ 42  43 /* 44  * 加载猜你喜欢推荐 45  */ 46 function loadCNXHRecommend(areaCode) { 47   var userId = "${sessionScope.sso_user_info.userName}"; 48   if(userId == null || userId == '') { 49     userId = ''; 50   } 51   $.ajax({ 52     data : { 53       areacode : areaCode, 54       userId : userId 55     }, 56     url : "<%=cnxh_domain%>ml/sale/querySortGoods", 57     dataType : "jsonp", 58     jsonp : "jsonpcallback", 59     success : function(json) { 60     /*    61       if(json.length == 0 && areaCode==1) { 62         $('#cnxh').css('display','none'); 63         return; 64       } */ 65        66       if(json.length == 0) { 67         $('#cnxh').css('display','none'); 68       } 69       var str = ""; 70       for (var i in json) { 71          72         str += '<a id="G10_rec_'+(Number(i)+1)+'" type="1" href="${shop_domain }/goods/${province.provinceId }_${city.cityId }_'+json[i].goodsId+'_1043600.html" target="_blank" title="'+json[i].goodsName+'" ><dl class="fixf">'+ 73         '<dd><img class="fl" width="70" height="70" src="${img_domain }/goods/'+json[i].picture+'_170x170.png" />'+ 74         '</dd><dt><h3>¥'+json[i].priceMin+'</h3><p>'+json[i].goodsName+'</p>'+ 75         '</dt></dl></a>'; 76       } 77        78       $('.related-recom-list').html(str); 79     } 80   }); 81 } 82 loadCNXHRecommend("${province.provinceId}"); 83  84  85  86 ------------------------------------------------------------------------------------------------------------------------------------------------------------ 87  88 getSearchHistoryData:function() { 89     var url = "shopSearch/searchHistory.json"; 90      91     $.ajax({ 92       type : "get", 93       url : url, 94       dataType : 'json', 95       cache:false, 96       success:function(json) { 97         if (json != null && json != "") { 98           $(searchHistory).empty(); 99           for ( var i in json) {100             var j=parseInt(i);101             $(searchHistory).append(template.replace(/\{NAME\}/ig,"<a id='historyWord_"+(++j)+"' style='display:block;' href='"+searchUrl+'?key='+json[i] + "&cityId="+settings.cityId+"&provinceId="+settings.provinceId+"' showname ='" + json[i] + "'>"+json[i]+"</a>"));102           }103           //$(searchHistory).append("<span class='" + settings.close_line + "'></span>");104           //$(searchHistory).append("<span class='" + settings.close_class + "'>关闭</span>");105           $(searchHistory).show();106         } else {107           $(searchHistory).empty();108         }109         json = null;110       }111     });112   },113   getPromptWordData:function(word) {114     var url = basePath+"shop_ajax_jsonp.json";115     $.ajax({116       type : "get",117       data : {'content':word,"areacode":settings.provinceId},118       url : url,119       dataType :"jsonp",120       jsonp : "jsonpcallback",121       success:function(json) {122         if (json != null && json != 'undefind' && json != "") {123           $(promptWord).empty();124           if (json.searchWord.length > 0) {125             for ( var i in json.searchWord) {126               var j=parseInt(i);127               if (json.searchWord[i].Word != undefined) {128                 $(promptWord).append($(promptTemplate.replace(/\{NAME\}/ig,"<a id='PromptWord_"+(++j)+"' style='display:block;' href='"+searchUrl+'?key='+json.searchWord[i].Word+"&cityId="+settings.cityId+"&provinceId="+settings.provinceId+"&no_re=1'showname = " + json.searchWord[i].Word +">"+json.searchWord[i].Word.replace(word,"<font color='red'>" + word + "</font>")+"</a>") ) );129               }130             }     131             $(promptWord).show();132           } else {133             $(promptWord).css("display" , "none");134           }135         } else {136           $(promptWord).hide();137         }138       }139     });140   }141 142 143 ------------------------------------------------------------------------------------------------------------------------------------------------------------144 145 146 function loadPage(flag){147   var nh=0;148   if(flag==2)149     nh=1;150   151   var content = $("#textfield").val();152   var sort = $("#sort").val();153   154   if(flag != 0)155     pageNo++;156   if(rec_flag==2&&flag==1&&content!=''){157     content=rectify;158     rec_flag=1;159   }160   $.ajax({161     type : "post",162     url : basePath + "serviceSearch",163     data : {164       "moduleType" : "1-1",165       'content' : content,166       'pageNo' : pageNo,167       'sort' : sort,168       'date' : new Date(),169       'nh' : nh170     },171     dataType : "json",172     success : function(json) {173       //$("#_collectionEle").attr("value","resultNum="+json.numFound+",nowPageNum="+pageNo);174       //_collect.behaviorAJAX(this);175 176       if(json.flag == 4){177         window.location.href=json.redirect;178       }179       180       181       $("#msgShow").find(".tips").text('');182       $("#msgShow").find(".tips").attr('class','');183       184       //纠错词185       if(json.rectify != "" && ($("#msgShow").html().indexOf('以下为您显示'))<0){186         $("#msgShow").append('<p class="tips content_biaoti">以下为您显示“<font color="#cc0000">'+json.rectify+'</font>” 的搜索结果。仍然搜索 <a href="#" onClick="loadPage(2)">'+json.key+'</a></p>');187         rectify=json.rectify;188         rec_flag=2;189       }190       //敏感词191       192       if(json.msg != "" && ($("#msgShow").html().indexOf('法律法规'))<0){193         $("#msgShow").append('<p class="tips content_biaoti">根据相关法律法规和政策,部分搜索结果未显示</font>');194       }195       196       if(json.obj.length!=0){197         $("#isLastPage").val("1");198         if(json.obj.length<20){199           $("#isLastPage").val("0");200         }201       202         if(json.flag == 0){203           var str = '';204           205           if(flag==0)206             $("#service-main").html('');207           208           for ( var i in json.obj) {209             str = '<div class="service clearfix"><a id="client_service_'+(Number(i)+1+(pageNo-1)*20)+'" type="1" onclick="saveKey(\''+content+'\');addCookie(\''+content+'\');jumpApp(\''+json.obj[i].jump_type+'\',\''+json.obj[i].func_id+'\',\''+json.obj[i].name+'\',\''+json.obj[i].url+'\',\''+json.obj[i].login_flag+'\');"><span class=" l"><img src='+json.obj[i].image+' width="41px" height="41px" /></span>'+210             '<p class=" l">'+json.obj[i].name_high+'</p><span class="icon_arrow r"></span></a></div>';211             $("#service-main").append(str);212           }213         }214       }else{215         deleteCookie(content);216         $("#isLastPage").val("0");217         $("#service-main").html(noResult);218         219       }220     }221   });222 }223 224 225 ------------------------------------------------------------------------------------------------------------------------------------------------------------226 227 function loadConditions(){228   var typeCode = $("#typeCode").val();229   $.ajax({230     type : "post",231     url : basePath + "listSearchConditions",232     data : {233       "typeCode" : typeCode,234       'date' : new Date()235     },236     dataType : "json",237     success : function(json) {238       if(json.flag == 0){239         $(".js-main").html('');240         var str = '';241         for ( var i in json.obj) {242           str = '<input type="hidden" name="keyIds" id="' + json.obj[i].keyID + '">'+243                '<input type="hidden" name="keyID" class="keyID" value="' + json.obj[i].keyID + '">'+244                '<div class="main_j cur_k" onclick="expanContract(\'' + json.obj[i].keyID + '\')">'+245                '<div class="main_title">'+246               '<h4 class="main_tit">' + json.obj[i].keyName + ':<span id="' + json.obj[i].keyID + '_title" class="js-bil" style="padding-left:8px; color:#e40077;">全部</span></h4>'+247               '<span class="triangle" id="span' + json.obj[i].keyID + '" ><img class="main_tii" src="' + basePath + 'images/touch/tip_h.png"></span> </div>'+248               '</div>'+249               '<div class="js-b" id="div' + json.obj[i].keyID + '" style="display: none">'+250               '<ul class="title_yy cont1_cont">'+251               '<li class="title_syy sy_ss cur_p _flag" '+252               'onclick="clickLi(\'' + json.obj[i].keyID + '\',\'' + "all" + '\',\'attrID'+ i + '\',\'全部\', this)" onmouseover="javascript:$(this).addClass(\'cl\');" onmouseout="javascript:$(this).removeClass(\'cl\');">'+253                '全部</li>';254           var _str = '';255           for ( var j in json.obj[i].listValue) {256             if(j<7){257               if(j != 0 && (j + 1) % 3 == 2){258                 _str += '<li class="title_syy"';259               }else{260                 _str += '<li class="title_syy sy_ss"';261               }262               263               _str += 'onclick="clickLi(\'' + json.obj[i].keyID + '\',\'' + json.obj[i].listValue[j].valueID + '\',\'attrID' + j + '\',\'' + json.obj[i].listValue[j].valueName + '\', this)" onmouseover="javascript:$(this).addClass(\'cl\');" onmouseout="javascript:$(this).removeClass(\'cl\');">'+264                   json.obj[i].listValue[j].valueName + '</li>';265             }else if(j==7){266                 _str += '<li class="title_syy"'+'onclick="gdClick('+json.obj[i].keyID +')" name="gdOpen'+json.obj[i].keyID +'" onmouseover="javascript:$(this).addClass(\'cl\');" onmouseout="javascript:$(this).removeClass(\'cl\');">更多</li>';267 268             }else if(j>7){269               if(j % 3 == 2){270                 _str += '<li class="title_syy" name="hid" style="display:none;" ';271               }else{272                 _str += '<li class="title_syy sy_ss" name="hid" style="display:none;"';273               }274               _str += 'onclick="clickLi(\'' + json.obj[i].keyID + '\',\'' + json.obj[i].listValue[j].valueID + '\',\'attrID' + j + '\',\'' + json.obj[i].listValue[j].valueName + '\', this)" onmouseover="javascript:$(this).addClass(\'cl\');" onmouseout="javascript:$(this).removeClass(\'cl\');">'+275                 json.obj[i].listValue[j].valueName + '</li>';276             }277           }278           str += _str;279           str += '</ul></div>';280           $(".js-main").append(str);281         }282       }283     }284   });285 }286 287 288 289 290 291 ------------------------------------------------------------------------------------------------------------------------------------------------------------292 /*293  * 商品数据页面加载294  */295 function loadPage(flag,f){//0添加数据,1追加数据296   var nh=0;297   if(flag==2)298     nh=1;299   var attrs = $("#attrs").val();300   var typeCode = $("#typeCode").val();301   var content = $("#textfield").val();302   303 304   if (rec2_flag==2 && flag==1 && content != ""){305     content = rectify;306     rec2_flag=1;307   }308   309   310   var sort = $("#sort").val();311   if(flag != 0)312     pageNo++;313   $.ajax({314     type : "post",315     url : basePath + "listResults",316     data : {317       "moduleType" : "1-1",318       "attrs" : attrs,319       "pageNo" : pageNo,320       "typeCode" : typeCode,321       "sort" : sort,322       "content" : content,323       'date' : new Date(),324       'nh' : nh325     },326     dataType : "json",327     success : function(json) {328       //$("#_collectionEle").attr("value","resultNum="+json.numFound+",nowPageNum="+pageNo);329       //_collect.behaviorAJAX(this);330       if(json.flag == 4){331         window.location.href=json.redirect;332       }333       334       $("#msgShow").find(".tips").text('');335       $("#msgShow").find(".tips").attr('class','');336       337       //纠错词338       if(json.rectify != "" && ($("#msgShow").html().(‘以下为您显示'))<0){339         $("#msgShow").append('<p class="tips content_biaoti">以下为您显示“<font color="#cc0000">'+json.rectify+'</font>” 的搜索结果。仍然搜索 <a href="#" onClick="loadPage(2)">'+json.key+'</a></p>');340         rectify=json.rectify;341         rec_flag=2;342         rec2_flag=2;343       } 344       345       //敏感词346       if(json.msg != "" && ($("#msgShow").html().indexOf('法律法规'))<0){347         $("#msgShow").append('<p class="tips content_biaoti">根据相关法律法规和政策,部分搜索结果未显示</font>');348       } 349       350       if(json.obj.length!=0){351         $("#paixu").css('display','block');352         $("#isLastPage").val("1");353         if(json.obj.length<20){354           $("#isLastPage").val("0");355         }356         if(json.numFound==20){357           $("#isLastPage").val("0");358         }359         if(json.flag == 0){360           if(flag == 0){361             $("#commodity_main").html("");362           }363           for ( var i in json.obj) {364             var url="";365             if(json.obj[i].root_catalog == 101 || json.obj[i].root_catalog == 128)366               url=$("#shouji_peijian").val()+json.obj[i].goods_id;367             if(json.obj[i].root_catalog == 146 || json.obj[i].root_catalog == 140)368               url=$("#taocan_yewu").val()+json.obj[i].goods_id;369             370             var str = '<div class="activity commode"><a id="client_goods_'+(Number(i)+1+(pageNo-1)*20)+'" type="1" class="  clearfix" onclick="saveKey(\''+content+'\');addCookie(\''+content+'\');" href="'371                 +url372                 +'" >'373                 + '<div class="pro_img l">'374                 + '<img class="" src="'375                 + $("#img_domain").val()376                 + '/goods/'377                 + json.obj[i].picture378                 + '_170x170.png"/></div>'379                 + '<div class="pro_stail">'380                 + '<h1>'381                 + json.obj[i].goods_name_high382                 + '</h1>'383                 + '<div class="dc"> <p class="instro">';384             if (json.obj[i].root_catalog == 101 || json.obj[i].root_catalog == 128) {385               str += json.obj[i].goods_subhead_high386                   + '</p></div><p class="price"><span>&yen;</span>'387                   +json.obj[i].min_price;388             }389             390             if (json.obj[i].root_catalog == 146 || json.obj[i].root_catalog == 140) {391               if(json.obj[i].min_price == json.obj[i].max_price){392                 str += json.obj[i].goods_subhead_high393                 + '</p></div><p class="price"><span>&yen;</span>'394                 +json.obj[i].min_price;395               }else{396                 str += json.obj[i].summary_high397                 + '</p></div><p class="price"><span>&yen;</span>'398                 +json.obj[i].min_price+399                 '-';400                 str += json.obj[i].max_price;401               }402             }403             str += '</p></div></a></div>';404             $("#commodity_main").append(str);405           }406         }407       }else if(f==1){408         //筛选无结果页面409         var str='<br/><br/><br/><br/><br/><br/><br/><br/><div class="article"><div class="tips_main"></div><div class="noresult"><p>抱歉,没有找到符合条件的搜索结果!</p></div></div>'410         $("#commodity_main").html(str);411         $('#flag_n').val(1);//筛选标识412         $("#isLastPage").val("0");//分页标识413       }else{414         deleteCookie(content);415         $("#isLastPage").val("0");416         $("#paixu").css('display','none');417         $("#commodity_main").html(noResult);418       }419     }420   });421 }422 423 424 ----------------------------------------------------------------------------------------------------------------------------------------------425 426 var basePath = "http://localhost:8087/open_api/";427 428 //var basePath = "http://se.richinfo.cn:20001/open_api/";429 430 var fun = {431   initObj : function(obj, callback) {432     fun.back_fun = callback;433     var user = obj.user;// 用户名434     var password = obj.password;// 密码435     var url = obj.url;// controller方法名436     var charset = obj.charset;// 编码437     var content = obj.content;// 关键字438     var category = obj.category;// 商品类别编码439     var province_id = obj.province_id;// 省440     var city_id = obj.city_id;// 市441     var sort = obj.sort;// 排序字段442     var pageNo = obj.pageNo;// 页码443     var pageSize = obj.pageSize;// 页数444     var group_field = obj.group_field;// 分组445     var channel = obj.channel;// 渠道446     var nh = obj.nh;447     $.ajax({448       url : basePath + url+".jsonp",449       data : {450         "user" : user,451         "password" : password,452         "charset" : charset,453         "content" : content,454         "category" : category,455         "province_id" : province_id,456         "city_id" : city_id,457         "sort" : sort,458         "pageNo" : pageNo,459         "pageSize" : pageSize,460         "group_field" : group_field,461         "channel" : channel,462         "nh" : nh463       },464       dataType : "jsonp",465       jsonp : "jsonpcallback",466       success : function(json) {467         fun.back_fun(json);468       }469     });470   },471   back_fun : function(obj) {472 473   }474 };475 476 477 /*var jsonMsg={478     "content":"4g",//关键词479     "charset":"",//编码480     "cagegory":"",//编码481     "url":"search",//方法名482     "province_id":"",//省地区编码483     "city_id":"",//市地区编码484     "sort":"",//排序485     "pageNo":"",//页码486     "pageSize":"",//一页数量487     "group_field":"",//分组488     "nh":"",//1 表示不对关键词处理489     "user":"zs",//用户名490     "password":"zs",//密码491     "channel":""//渠道492 };*/493 494 var jsonMsg={495     "user":"zs",//1关键词496     "password":"zs",497     "channel":"10000",498     "url":"search",499     "city_id":"100",500     "province_id":"100",501     "content":"4g"502 };503 //回调函数 obj 返回结果数据504 function fn_cb(obj){505   alert(obj.msg);506   //业务处理507 }508 fun.initObj(jsonMsg, fn_cb);

 

dataType:预期服务器返回的类型:

      

  • "
  • "html": 返回纯文本 HTML 信息;包含的 script 标签会在插入 dom 时执行。
  • "script": 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 "cache" 参数。注意:在远程请求时(不在同一个域下),所有 POST 请求都将转为 GET 请求。(因为将使用 DOM 的 script标签来加载)
  • "json": 返回 JSON 数据 。
  • "jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。
  • "text": 返回纯文本字符串

 

data

类型:String

发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。