2015-07-21 68 views
2

我想通過ajax POST請求從Python傳遞一個字符串到Javascript,但我發現了嚴重的困難。從Python傳遞一個字符串到Javascript

我已經嘗試使用和不使用JSON。

下面的代碼

JAVASCRIPT

$.ajax({ 
    url: url, #url of the python server and file 
    type: "POST", 
    data: {'data1': "hey"}, 
    success: function (response) { 
     console.log(" response ----> "+JSON.parse(response)); 
     console.log(" response no JSON ---> " +response); 
    }, 
    error: function (xhr, errmsg, err) { 
     console.log("errmsg"); 
    } 
}); 

的Python

import json 
print "Access-Control-Allow-Origin: *"; 
if form.getvalue("data1") == "hey": 
     out = {'key': 'value', 'key2': 4} 
     print json.dumps(out) 

結果是一個空的JSON。當我在JavaScript中執行類似JSON.parse的操作時,出現輸入錯誤的意外結束,並且當我嘗試獲取響應數據的長度時,我得到的大小爲0. 我想應該會出現客戶端的某些問題服務器通信(我使用CGIHTTPServer)或者可能是python或javascript期望的數據類型有問題。

我也試過沒有JSON,喜歡的東西 的Python

print "heyyyyy" 

的Javascript

alert(response) //case of success 

,但我也得到一個空字符串。

您能否給我一些處理這個問題的建議? 非常感謝!

+0

你不應該使用打印。 – rolodex

回答

1

我設法解決這個問題使用方法類HTTPResponse來自Django框架。

現在是(用JSON回答客戶端)的東西非常相似,這

PYTHON

from django.http import HttpResponse 
... 
data = {} 
data['key1'] = 'value1' 
data['key2'] = 'value2' 
..... 
response = HttpResponse(json.dumps(data), content_type = "application/json")  
print response; 

JAVASCRIPT(Retireving和閱讀JSON)

success(response) 
    alert(JSON.stringify(response)); 

或者,如果我只是想發送一個字符串或一個沒有JSON的整數

PYTHON(no JSON)

response = HttpResponse("ayyyyy", content_type="text/plain") 
print response 

JAVASCRIPT(檢索字符串或值)

success: function (response) { 
    alert(response); 

這個作品非常好,這是非常可讀的,在我看來簡單!

0

相反的print json.dumps(out),你應該使用return json.dumps(out)

print只會在Python的控制檯顯示它,就像在JavaScript console

+0

'json.dumps(out)'只能轉換成一個字符串,沒有別的。它確實看起來像印刷是去http://uthcode.blogspot.com/2009/03/simple-cgihttpserver-and-client-in.html – bbill

+0

抱歉。應該「返回」 – rolodex