問題描述
注意:我粘貼了比 ajax 調(diào)用更多的代碼,以防代碼是(部分)導(dǎo)致問題的原因.但是,我不認(rèn)為是這樣,因此您最好將注意力集中在 ajax
和 jAjax
函數(shù)上.
另請(qǐng)注意,由于對(duì)此問題的評(píng)論(帶有贊成票)說(shuō)我的代碼難以破譯,我很樂意澄清需要澄清的內(nèi)容,如果這可以證明是找到問題的關(guān)鍵.
謝謝.
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.
事情就是這樣.我正在嘗試放棄 jQuery,因?yàn)槲椅ㄒ皇褂玫氖?$.ajax()
方法,并且包括像 jQuery 這樣的整個(gè)庫(kù)僅用于 1 個(gè)功能是 IMO 瘋狂的.我什至不需要 $.ajax
方法的全部功能,因此我編寫了自己的 ajax
函數(shù).
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.
問題是:它不起作用,我似乎無(wú)法弄清楚原因.我正在嘗試將對(duì)象發(fā)送到服務(wù)器(特別是:控制器中的 ajaxAction - 使用 Zend FW).下面是 javascript 代碼,以及 firebug 控制臺(tái)告訴我的內(nèi)容的摘要.
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(/^ss*/, '').replace(/ss*$/, '');
};
}
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);
}
});
}
我嘗試發(fā)出 Ajax 請(qǐng)求的四種方式:
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
jAjax({data:{foo:'bar'}},getUrl());
:這很好用:
[]{"ajax":true,"controller":"index","action":"ajax","module":"default","identity":{},"data":{"foo:酒吧"}}參數(shù):data[foo] 'bar' 來(lái)源:data%5Bfoo%5D=Bar(來(lái)自 FB 控制臺(tái)的 POST 選項(xiàng)卡)頭文件:application/x-www-form-urlencoded;字符集=UTF-8
所有這些都發(fā)送到以下網(wǎng)址:http://www.foo.bar/index/ajax?data%5Bfoo%5D=bar
[]{"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
但是這不起作用:
This doesn't work, however:
[]{"ajax":true,"controller":"index","action":"ajax","module":"default","identity":{}} 是響應(yīng)FB 中的 POST 選項(xiàng)卡:JSON 數(shù)據(jù):{foo:'Bar'} 源:{"data":{"Foo":"Bar"}}(但相同的 url 是 case 1)標(biāo)題:json;字符集=UTF-8
[]{"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
這是最重要的:完整的請(qǐng)求 url 與案例 1 中的 url 相同,標(biāo)題也是如此,但當(dāng)我查看 POST 選項(xiàng)卡時(shí)在 FB 控制臺(tái)中(檢查請(qǐng)求)這是我能找到的唯一區(qū)別:
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: 參數(shù):data[foo] 'bar' 來(lái)源:data%5Bfoo%5D=Bar
在這種情況下,我看不到參數(shù)部分,只有:來(lái)源:data%5Bfoo%5D=Bar
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
與 case2 相同,除了 url,我想我忘記通過 encodeURI
傳遞.這個(gè)案子現(xiàn)在不太重要.我想/希望我能在弄清楚案例 3 有什么問題的那一刻開始工作.
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.
在所有 4 種情況下,請(qǐng)求都被發(fā)送和接收.控制器動(dòng)作如下:
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??');
}
}
因?yàn)槲沂盏揭粋€(gè) JSON 字符串,所以我確定請(qǐng)求已發(fā)布,并且具有正確的 XMLHttpRequest
標(biāo)頭.那么,為什么我不能發(fā)布 JSON 對(duì)象?更重要的是:為什么情況 3 不起作用?我不知道 jQuery 在做什么?是什么使案例 1 起作用,而案例 3 不起作用?
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:這可能無(wú)關(guān)緊要,但在瘋狂的時(shí)刻我嘗試添加:ret.setRequestHeader('Connection','close');
到 ajax
函數(shù),但我注意到,在發(fā)送的標(biāo)頭中,Connection
設(shè)置為保持活動(dòng)狀態(tài).也許這可以讓某人知道出了什么問題?
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?
提前致謝
推薦答案
如果有人想知道出了什么問題:
In case anybody wonders what was wrong:
ret.setRequestHeader('Content-type', 'application/x-www-form-urlencode');
應(yīng)該是x-www-form-urlencoded",最后是d":
Should have been "x-www-form-urlencoded", with a "d" in the end:
ret.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
發(fā)送一個(gè)形式化對(duì)象現(xiàn)在可以工作了,我可以擺脫 jQuery :-)
sending a formalized object is now working, and I can get rid of jQuery :-)
這篇關(guān)于JavaScript Ajax 請(qǐng)求 vs jQuery $.ajax的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!