2016-04-15 33 views
0

我想通過Ajax向Django服務器發送「GET」和「POST」請求。 首先,我公司提供的URL配置:Django - Ajax:在數據中發送url參數

url(r'^write_to_file/(?P<file_name>.*)/(?P<content>.*)/$',generalFunctions.write_to_file, name ='write_to_file'), 

現在,AJAX的一部分。以前,我用來做什麼的這樣(避免在數據發送PARAMS)

$.ajax({ 
     type: "GET", 
     url: '/write_to_file/' + file_name + '/' + content , 
     data: {}, 
     success: function(data){ 
      alert ('OK'); 
     }, 
     error: function(){ 
      alert("Could not write to server file " + file_name) 
     } 
    }); 

截至某一時刻,我用這種方法滿足,但現在對我來說,在FILE_NAME和內容通過傳遞是非常重要的「數據」變量和由於某種原因,我得到404錯誤。

$.ajax({ 
     type: "GET", 
     url: '/write_to_file/', 
     data: {'file_name':file_name, 'content':content}, 

     success: function(data){ 
      alert ('OK'); 
     }, 
     error: function(){ 
      alert("Could not write to server file " + file_name) 
     } 
    }); 

錯誤在服務器端:

Not Found: /write_to_file/ 
[15/Apr/2016 14:03:21] "GET /write_to_file/?file_name=my_file_name&content=my_content HTTP/1.1" 404 6662 

錯誤的客戶端:

jquery-2.1.1.min.js:4 GET http://127.0.0.1:8000/write_to_file/?file_name=my_file_name&content=my_content 404 (Not Found)

任何想法,爲什麼? ajax語法有什麼問題,或者它與URLConf有什麼關係?

回答

3
url(r'^write_to_file/(?P<file_name>.*)/(?P<content>.*)/$',generalFunctions.write_to_file, name ='write_to_file'), 

現在是錯誤的,您要發送的POST請求的URL是:/ write_to_file/

url(r'^write_to_file/$',generalFunctions.write_to_file, name ='write_to_file'), 

是你想要我的想法!

+0

好吧,它沒有更多的404錯誤,但我有505錯誤,而不是原來的視圖本身(我在功能的開始放置一個斷點,調試器沒有達到那一點)。現在的錯誤是TypeError:write_to_file()只需3個參數(給出1) [15/Apr/2016 14:20:48]「GET/write_to_file /?file_name = my_file_name&content = my_content HTTP/1.1」500 16010 –

+2

這真的應該很明顯:如果您不再將這些值傳遞到URL中,則需要將它們作爲參數移除到函數中。 –

+0

是的,你也定義了你的write_to_file視圖,你需要刪除除了請求之外可能聲明的任何參數。例如def write_to_file(request,file_name,content):...應該成爲def write_to_file(request):... –