Sun*_*Red 5 reflection ajax jquery
我正在开发一个基于ajax的应用程序,并想知道反射在这里扮演或可能扮演什么角色?
可能最重要的是我问自己,这是否是一个很好的方法
这是一个萌芽的程序吗?想到什么是利弊?
我目前的实施,我不满意,看起来像这样.
这是一个例子
function setGamedayScoringChangeHandlers() {
    $("#community").delegate("div.community div.nav", "click", function() {
        var orderId = $(this).html();
        var communityId = $(this).closest('.communityView ').dashId();
        requestGamedayScoringByOrderId(communityId, orderId);
    });
}
function requestGamedayScoringByOrderId(communityId, orderId) {
    var $targetContainer = $('#community-' + communityId + '-gameday');
    $.ajax({
        url: '?api=league&func=getGamedayScoringByCommunityIdAndOrderId',
        data: {
            communityId : communityId,
            orderId : orderId
        },
        success: function(result) {
             // custom indicator, that sth. didn't work as supposed 
             if (result.success === false) {
                 // a php error couldn't be handled as expected
                 if (result.error === 'phpRuntimeError') {
                      // ..
                 }
             // ..
             }
             else {
                 renderGamedayScoring(result, $targetContainer);
             }
        }
    });
 }
如何简化冗余错误检查?反思,在某种意义上:"响应是否有效?错误消息说什么或数据是什么样的?" 做一个合理的结构吗?另外:实际的ajax请求的"耦合"和确定$ targetContainer是"正常"的过程吗?
非常感谢,
罗布森
是的,我认为通过一个管道注册ajax处理程序是一种好方法,因为它更容易控制,您将拥有更少的冗余代码和更少的登机效果。如果我查看您的代码注释,似乎响应并不符合您的预期。我曾经这样做来控制一组与服务器脚本通信的ajax请求。我构建一个请求对象,例如:
    // myscript.js
var rqPHP = {
            url:'php/dispatcher.php', type:'POST', dataType:'json',
            success:function(json, status, jXHR){
                //console.log('rqPHP.succes : ', json);
                if(!json)   return console.warn('[rqPHP.success] json is null');
                if(!json.cmd)   return console.warn('[rqPHP.success] json.cmd is null');
                if(!json.res)   return console.warn('[rqPHP.success] json.res is null');
                if(json.err && json.err.length){        console.warn('[rqPHP.success errors cmd:'+json.cmd+'] '+json.err);}
                // so if no errors, dispatch actions based on original command asked
                switch(json.cmd){
                    case 'loadfile' :
                        // do whatever with response
                        break;
                    case 'savefile' :
                        // do whatever with response
                        break;
                }
            },
            error:function(jXHR, status, err){
                console.warn('[rqPHP.error] ', status,',',err,',',jXHR.responseText);
            }
        };
然后,当使用这个对象时,我会执行所有不同的操作组,并且我会精确地传递我所传递的操作和参数。我过去常常请求 json 数据,这样我就能够收到一个简单的解析响应,这样我就能够返回所请求的原始命令,以及可能发生的错误的一些详细信息,例如,以及何时需要触发请求:
// myscript.js
rqPHP.data = {'cmd':'loadfile', 'filename':'file.dat', 'arg2':'other argument'};
$.ajax(rqPHP);
然后是一个将响应的服务器脚本的示例:
// dispatcher.php    
    $pv = $_POST;
    $res = '';
    $err = array();
    // you check the command asked for :
    switch(strtolower($pv['cmd'])){
      case 'savefile' :
        // do whatever
        break;
      case 'loadfile' :
        // do whatever
        if(any error){
          $err[] = $loadError;// push error with whatever details you'll retrieve in javascript
       }else{
         $res = ',"res":"'.$dataLoaded.'"';// format json response so you'll check the var exist
        }
        break;
    }
    $jsonRes = '{"cmd":"'.$pv['cmd'].'"'.$res.',"err":"'.implode('|', $err).'"}';// json result
    print $jsonRes;
它们可能有一些错误,这只是原则性的,我希望能有所帮助,只是一些最后的建议:
如果您计划为不同的部分触发许多负载(我的意思是您可能不会在加载新部分之前等待 ajax 的响应),那么最好设置主要的成功和错误函数以保持集中,然后构建一个新请求每次加载时对象
function rqSuccess(json, status, jXHR){
   // put same checking code as before, then you can also retrieve some particular variables
   // here, 'this' should correspond to the request object used for the $.ajax so :
   console.log('myTarget is : ', this.myTarget, ' , myVariable is : ', this.myVariable);
}
function rqError(jXHR, status, err){
   // put same checking code 
}
// then each time you want make one or many independant calls, build a new request object
var myRq = {url:'dispatcher.php',type:'POST',dataType:'json',
    success:rqSuccess,
    error:rqError,
    myTarget:$('#myblock'),// any variable you want to retrieve in response functions
    myVariable:'Hello !',// after all it is an object, you can store anything you may need, just be carefull of reserved variables of the ajax object (see jQuery $.ajax doc)
    // the data object is sanitized and sended to your server script, so put only variables it will need
    data : {'cmd':'loadfile',...}
}
$.ajax(myRq);
// you may load an other independant one without waiting for the response of the first
var myRq2 = {...myTarget:$('#anotherblock'), data:{'cmd':'anotheraction'}...}
$.ajax(myRq2);
| 归档时间: | 
 | 
| 查看次数: | 343 次 | 
| 最近记录: |