JavaScript的Ajax请求VS jQuery的$。阿贾克斯 [英] JavaScript Ajax request vs jQuery $.ajax

查看:303
本文介绍了JavaScript的Ajax请求VS jQuery的$。阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我更贴code不仅仅是Ajax调用,在起飞的机会,code是(部分)是什么导致了问题。我不认为它是,但是,所以你可能会更好过集中于 AJAX jAjax 功能后面一点。
还要注意的是,因为有一个注释(带upvote)在这个问题上说我的code是难以破译,我会高兴地澄清什么需要澄清如果能证明是关键在发现问题。
感谢。


这里的东西。我想沟jQuery的,因为我使用的唯一的事情就是 $。阿贾克斯()法,其中包括一个完整的LIB像jQuery的只有1功能是IMO疯狂。我甚至都不需要的 $。阿贾克斯全功能的方法,无论如何,所以我写我自己 AJAX 功能。

现在的问题是:它不工作,我似乎无法找出原因。我试图将对象发送到服务器(特别是:ajaxAction控制器 - 使用Zend FW)。下面是JavaScript code,和什么样的萤火虫控制台告诉我一个总结。

 如果(!String.prototype.trim)
{
    String.prototype.trim =功能()
    {
        使用严格;
        返回this.replace(/ ^ \ S \ S * /,'').replace(/ \ s \ S * $ /,'');
    };
}

功能的getURL(动作控制器)
{
    VAR基地,URI;
    基地= window.location.href.replace('HTTP://'+window.location.host,'');
    如果(base.length→1)
    {
        基地= base.substring(1,base.length).split('/');
        控制器=控制器||基[0];
        基地[0] =控制器||基[0];
        基地[1] =动作||基[1];
        回归/'+base.join('/');
    }
    控制器=控制器|| '指数';
    行动=行动|| AJAX;
    返回基地+控制器+/+行动;
}

功能formalizeObject(OBJ,递归)
{
    递归=递归||假;
    如果(typeof运算的obj!= ='对象')
    {
        抛出新的错误(没有提供任何对象');
    }
    VAR RET ='';
    为(在OBJ变种I)
    {
        如果(!obj.hasOwnProperty(I)|| typeof运算OBJ [I] ===功能)
        {
            继续;
        }
        如果(递归)
        {
            RET + ='['+ I +];
        }
        其他
        {
            保留+ =(ret.length大于0'和;':'')+ i.toString();
        }
        如果(typeof运算OBJ [I] ===对象)
        {
            保留+ = formalizeObject(物镜[I]中,真);
            继续;
        }
        RET + ='='+ OBJ [I]的ToString();
    }
    如果(递归)
    {
        返回RET;
    }
    返回EN codeURI(RET);
}

功能成功()
{
    如果(this.readyState === 4和&安培; this.status === 200)
    {
        执行console.log(this.responseText);
    }
}

功能AJAX(STR,网址,方法,JSON)
{
    VAR RET;
    JSON = JSON ||假;
    海峡=海峡|| {};
    方法=方法|| POST;
    URL =网址||的getURL();
    海峡=
    STR =(typeof运算海峡===对象STR:{数据:STR});
    尝试
    {
        RET =新XMLHtt prequest();
    }
    赶上(错误)
    {
        尝试
        {
            RET =新的ActiveXObject(MSXML2.XMLHTTP);
        }
        赶上(错误)
        {
            尝试
            {
                RET =新的ActiveXObject(Microsoft.XMLHTTP);
            }
            赶上(错误)
            {
                抛出新的错误(不支持Ajax?');
            }
        }
    }
    如果(typeof运算RET!=='对象')
    {
        抛出新的错误(不阿贾克斯,农民田间学校);
    }
    ret.open(方法,URL,真正的);
    ret.setRequestHeader(X-要求,随着','XMLHtt prequest');
    ret.setRequestHeader(内容型,(JSON应用/ JSON:应用程序/ x-WWW的形式urlen code'));
    ret.onreadystatechange =成功;
    ret.send((JSON JSON.stringify(STR):formalizeObject(STR)));
    返回true;
}

功能jAjax(STR,网址)
{
    $阿贾克斯(
    {
        网址:网址,
        数据:海峡,
        键入:POST,
        成功:函数(RES)
        {
            执行console.log(RES);
        }
    });
}
 

四种方式中,我已努力使Ajax请求:

  jAjax({数据:{FOO:'棒'}}中,getURL()); // 1
jAjax({数据:{FOO:'棒'}}中,getURL(),TRUE); // 2
阿贾克斯({数据:{FOO:'棒'}}中,getURL()); // 3
阿贾克斯({数据:{FOO:'棒'}}中,getURL(),TRUE); // 4
 

  1. jAjax({数据:{FOO:'棒'}}中,getURL()); :这只是正常:

      

    []{"ajax":true,"controller":"index","action":"ajax","module":"default","identity":{},"data":{"foo":"Bar"}}   参数:data [FOO]'酒吧'和来源:资料%5Bfoo%5D =酒吧(从FB控制台POST选项卡)   标题:应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8
      所有这一切都被发送到以下网址: http://www.foo的.bar /索引/ AJAX?数据%5Bfoo%5D =栏

  2. 这是不行的,但是:

      

    [] {AJAX:真正的控制器:指数,行动:阿贾克斯,模块:默认,身份:{}}是响应   在FB POST标签:JSON数据:{FOO:'酒吧'}来源:{数据:{富:酒吧}}(但相同的URL是区分1)   标题:JSON;字符集= UTF-8

  3. 这是很大的一个:完整的请求URL相同的情况下,1至的URL,因为是头,但是当我看着POST标签在FB控制台(检查请求),这是唯一的区别我能找到的:

      

    案例1:参数:data [FOO]'吧来源:资料%5Bfoo%5D =酒吧
      在这种情况下,我看不到的参数部分,只有:来源:资料%5Bfoo%5D =酒吧

  4. 相同,除了网址,我想我忘了通过连接codeURI 来情况2。对于现在这种情况是不那么重要了。我想/希望我会得到这个工作的那一刻我弄清楚什么是错的情况下3

在所有4个的情况下,请求被发送,和接收的。该控制器操作如下:

 公共职能ajaxAction()
{
    $这个 - > _helper->布图设计> disableLayout();
    $这个 - >调用getHelper('ViewRenderer的) - > setNoRender();
    $这个 - > _helper->调用getHelper('AjaxContext') - > addActionContext(AJAX,JSON)
                                             - >调用initContext(JSON);
    如果($这 - >调用getRequest() - > isPost()&安培;&安培; $这 - >调用getRequest() - > isXmlHtt prequest())
    {
        回声json_en code(array_merge(阵列('阿贾克斯'=>真),$这个 - > _getAllParams()));
    }
    其他
    {
        抛出新的异常(没有Ajax调用做?');
    }
}
 

由于我收到一个JSON字符串,我敢肯定,要求张贴,并具有正确的 XMLHtt prequest 头。那么,为什么我不能发表JSON对象?甚至更重要的是:为什么是3的情况下不能正常工作?什么是jQuery的这样做,我不知道吗?是什么,使案件1工作,但不区分3?

PS:这可能是无关紧要的,但在疯狂的时刻,我尝试添加这样的: ret.setRequestHeader('连接','关闭'); AJAX 的功能,但我注意到,在被罚出了头,连接设置为保持活动的所有相同。或许这给了别人一个线索,问题出在哪里?

在此先感谢

解决方案

在任何情况下,想知道什么是错的:

  ret.setRequestHeader(内容类型,应用程序/ x-WWW的形式urlen code');
 

本来应该是X WWW的形式,urlen codeD,在结束了D:

  ret.setRequestHeader(内容类型,应用程序/ x-WWW的形式urlen codeD');
 

发送的正式的对象是现在的工作,我可以摆脱的jQuery: - )

NOTE: I've pasted more code than just the ajax calls, on the off chance that code is (part of) what's causing the problem. I don't think it is, however, so you're probably better off focussing on the ajax and jAjax functions a bit further down.
Also note that, since there's a comment (with upvote) on this question saying my code is hard to decipher, I'd happily clarify what needs clarifying if that could prove to be the key in finding the problem.
Thanks.


Here's the thing. I'm trying to ditch jQuery, since the only thing I use is the $.ajax() method, and including an entire lib like jQuery for just 1 feature is IMO crazy. I don't even need the full functionality of the $.ajax method anyway, hence I wrote my own ajax function.

The problem is: it's not working, and I can't seem to figure out why. I'm trying to send objects to the server (specifically: ajaxAction in the controller - using Zend FW). Below is the javascript code, and a summary of what the firebug console tells me.

if (!String.prototype.trim)
{
    String.prototype.trim = function()
    {
        "use strict";
        return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    };
}

function getUrl(action,controller)
{
    var base,uri;
    base = window.location.href.replace('http://'+window.location.host,'');
    if (base.length > 1)
    {
        base = base.substring(1,base.length).split('/');
        controller = controller || base[0];
        base[0] = controller || base[0];
        base[1] = action || base[1];
        return '/'+base.join('/');
    }
    controller = controller || 'index';
    action = action || 'ajax';
    return base+controller+'/'+action;
}

function formalizeObject(obj,recursion)
{
    recursion = recursion || false;
    if (typeof obj !== 'object')
    {
        throw new Error('no object provided');
    }
    var ret = '';
    for (var i in obj)
    {
        if (!obj.hasOwnProperty(i) || typeof obj[i] === 'function')
        {
            continue;
        }
        if (recursion)
        {
            ret +='['+i+']';
        }
        else
        {
            ret += (ret.length > 0 ? '&' : '') + i.toString(); 
        }
        if (typeof obj[i] === 'object')
        {
            ret += formalizeObject(obj[i],true);
            continue;
        }
        ret += '='+obj[i].toString();
    }
    if (recursion)
    {
        return ret;
    }
    return encodeURI(ret);
}

function success()
{
    if (this.readyState===4 && this.status===200)
    {
        console.log(this.responseText);
    }
}

function ajax(str,url,method,json)
{
    var ret;
    json = json || false;
    str = str || {};
    method = method || 'POST';
    url = url || getUrl();
    str = 
    str = (typeof str === 'object' ? str : {data:str});
    try
    {
        ret = new XMLHttpRequest();
    }
    catch (error)
    {
        try
        {
            ret= new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch(error)
        {
            try
            {
                ret= new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch(error)
            {
                throw new Error('no Ajax support?');
            }
        }
    }
    if (typeof ret !== 'object')
    {
        throw new Error('No Ajax, FFS');
    }
    ret.open(method, url, true);
    ret.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    ret.setRequestHeader('Content-type', (json ? 'application/json' : 'application/x-www-form-urlencode'));
    ret.onreadystatechange = success;
    ret.send((json ? JSON.stringify(str) : formalizeObject(str)));
    return true;
}

function jAjax(str,url)
{
    $.ajax(
    {
        url : url,
        data: str,
        type: 'POST',
        success: function(res)
        {
            console.log(res);
        }
    });
}

Four ways in which I've tried to make the Ajax request:

jAjax({data:{foo:'bar'}},getUrl());//1
jAjax({data:{foo:'bar'}},getUrl(),true);//2
ajax({data:{foo:'bar'}},getUrl());//3
ajax({data:{foo:'bar'}},getUrl(),true);//4

  1. jAjax({data:{foo:'bar'}},getUrl());: This works just fine:

    []{"ajax":true,"controller":"index","action":"ajax","module":"default","identity":{},"data":{"foo":"Bar"}} Parameters: data[foo] 'bar' And Source: data%5Bfoo%5D=Bar (from POST tab in FB console) Header: application/x-www-form-urlencoded; charset=UTF-8
    All of this was sent to the following url: http://www.foo.bar/index/ajax?data%5Bfoo%5D=bar

  2. This doesn't work, however:

    []{"ajax":true,"controller":"index","action":"ajax","module":"default","identity":{}} is the response POST tab in FB: JSON data: {foo:'Bar'} source: {"data":{"Foo":"Bar"}} (but same url is case 1) Header: json; charset=UTF-8

  3. This is the big one: the full request url is identical to url from case 1, as are the headers BUT when I look at the POST tab in the FB console (inspect the request) This is the only difference I can find:

    case 1: Parameters: data[foo] 'bar' Source: data%5Bfoo%5D=Bar
    In this case, I can't see the Parameters section, only: Source: data%5Bfoo%5D=Bar

  4. Identical to case2, except for the url, which I think I forgot to pass through encodeURI. This case is less important for now. I think/hope I'll get this working the moment I figure out what's wrong with case 3.

In all 4 cases, the request is sent, and received. The controller action is as follows:

public function ajaxAction()
{
    $this->_helper->layout->disableLayout();
    $this->getHelper('viewRenderer')->setNoRender();
    $this->_helper->getHelper('AjaxContext')->addActionContext( 'ajax' , 'json' )
                                            ->initContext('json');
    if($this->getRequest()->isPost() && $this->getRequest()->isXmlHttpRequest())
    {
        echo json_encode(array_merge(array('ajax'=>true),$this->_getAllParams()));
    }
    else
    {
        throw new Exception('no ajax call made??');
    }
}

Since I'm receiving a JSON string, I'm sure the request is posted, and has the correct XMLHttpRequest header. Why then, can't I post JSON objects? Even more to the point: why is case 3 not working? What is jQuery doing that I'm not aware of? What is it, that makes case 1 to work, but not case 3?

PS: It might be irrelevant, but in a moment of madness I tried adding this: ret.setRequestHeader('Connection','close'); to the ajax function, but I noticed that, in the header that got sent out, Connection was set to keep-alive all the same. Perhaps this gives someone a clue as to what went wrong?

Thanks in advance

解决方案

In case anybody wonders what was wrong:

ret.setRequestHeader('Content-type', 'application/x-www-form-urlencode');

Should have been "x-www-form-urlencoded", with a "d" in the end:

ret.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

sending a formalized object is now working, and I can get rid of jQuery :-)

这篇关于JavaScript的Ajax请求VS jQuery的$。阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆