1. 程式人生 > >AJAX 非同步傳輸資料的問題

AJAX 非同步傳輸資料的問題

要非同步傳輸的資料:

Xml程式碼 複製程式碼
  1. ....       
  2. <actionxsi:type="basic:JavaScript"script="index += 1;"/>
  3. ....  

 Ajax非同步傳輸程式碼:

Js程式碼 複製程式碼
  1. var postData = "input="+ escape(inputJSON) +"&script="+escape(xml)+  
  2.                    "&feedGeneral=" + escape(feedGeneral);  
  3. XmlHttpRequest.open("POST",url,true);  
  4. XmlHttpRequest.setRequestHeader("Content-Type"
    ,"application/x-www-form-urlencoded");  
  5. XmlHttpRequest.send(postData);  

 postData在encode和unencode,最終導致在後臺Servlet中得到得到資料+被空格代替,使得script中的index += 1;變成了index =  1;從而導致後臺Java程式碼在跑script出現死迴圈。
在網上搜索,發現content-type使用application/x-www-form-urlencoded後:

Control names and values are escaped. Space characters are replaced by `+', and then reserved characters are escaped as 

described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal 

digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., `%0D%0A'). 

 然而使用form來提交方式來發起request卻不會出現類似的問題,而form預設的Content-Type也是application/x-www-form-urlencoded:

Js程式碼 複製程式碼
  1. $('test').innerHTML = "<form target='_blank' id='test_form' action='./gen_feed' method='post'>"
  2.         + "<input type='text' name='input' /><input type='text' name='script' />"
  3.         + "<input type='text' name='feedGeneral' /><input type='hidden' name='format' value='" + 
    this.feed_type + "'   
  4. />"  
  5.         + "<input type='submit' value='gen' /></form>";  
  6. var test_form = $('test_form');  
  7. test_form.elements[0].value = inputJSON;  
  8. test_form.elements[1].value = script;  
  9. test_form.elements[2].value = feedGeneral;  
  10. test_form.submit();  

 仍未發現問題到底出在何處,暫做備忘。暫時把script中的‘+’都用‘-’代替,index += 1;改成index -= -1;呵呵,以後有人看到這段自動生成的詭異指令碼,不知道會作何感想,但現在也只能如此。