2011-01-25 56 views
1

由於跨域問題,我有一個通過JSONP使用的休息api,我實現了一個錯誤記錄器來捕獲頁面和帖子上發生的每一個錯誤它給服務器 的URI錯誤記錄器是一樣的東西:Rest API:在REST中傳遞window.location.href uri

user/{userId}/message/{errorMessage}/browser/{browser}/browserVer/{browserVer}/secure/{secure}/os/{os}/location/{location}" 

位置變量是有問題的,我怎麼能傳遞window.location.href在URI?

我試過escape,encodeuri,encodeuricomponent我必須base64它嗎? 感謝

回答

0

URI的轉義序列在RFC2396的section 2.4.1定義(統一資源標識符):

An escaped octet is encoded as a character triplet, consisting of the 
percent character "%" followed by the two hexadecimal digits 
representing the octet code. For example, "%20" is the escaped 
encoding for the US-ASCII space character. 

    escaped  = "%" hex hex 
    hex   = digit | "A" | "B" | "C" | "D" | "E" | "F" | 
         "a" | "b" | "c" | "d" | "e" | "f" 

本RFC還定義了path組分保留字符在section 3.3

Within a path segment, the characters "/", ";", "=", and "?" are reserved. 

所以您需要使用encodeURIComponent(),因爲escape()已被deprecatedencodeURI()does not escape all reserved characters需要按照上面的RFC摘錄進行轉義。

下面的例子表明,只有encodeURIComponent()是正確轉義斜槓(這些是最可能的原因,你所面臨的問題的字符):

>>> escape('//'); 
"//" 

>>> encodeURI('//'); 
"//" 

>>> encodeURIComponent('//'); 
"%2F%2F" 

但是請注意,如果可能的話,你應該使用POST而不是GET。這是在REST(以及通常)中使用的正確方法,因爲您正在將數據從客戶端發送到服務器(POST),而不是從服務器(GET)獲取它們。

使用POST還可以讓您避免一個額外的問題。由於URI的長度在普通Web服務器中是有限的,所以遲早你會遇到一個具有很長URI的請求,這個請求會被修剪或者拋出一個錯誤。切換到POST將允許您保持URI乾淨並將數據保留在消息正文中而不是URI中。有關URI長度限制的詳細信息,請參閱answers to this question

+0

謝謝你的詳細答案,我會嘗試找出有問題的字符,也許只是刪除它們。我不能移動到後期艱難,因爲我在JSONP工作 – Amnon 2011-01-26 07:59:16