所以我试图让一个基于web.py的python webservice在jQuery对它进行ajax调用之后通过JSONP发回一个列表对象。
问题是在阅读了很多例子后,我仍然无法理解如何使其发挥作用。以下是我与atm合作的代码:
使用Javascript:
xmlrpcproxy = 'http://0.0.0.0:1885/'; //Back To The Future III reference on the port :)
jQuery.ajaxSetup ({
url: xmlrpcproxy, // <--- returns valid json if accessed in the browser
type: "GET",
cache: false,
contentType: "jsonp", // Pay attention to the dataType/contentType
dataType: 'jsonp', // Pay attention to the dataType/contentType
});
jQuery.ajax({
success: function(data) {
console.log("You made it!");
},
error: function (xhr) {
console.log("Error: " + xhr.statusText);
}
}).done(function(data){
console.log(data);
var firstoption = '<option value="select" selected>Please Select</option>';
jQuery("select#ItemIDSelect").html(firstoption);
var i;
var erplist = JSON.parse(data);
jQuery("responsearea").append(erplist);
for (i = 0; i < erplist.length; ++i) {
jQuery("select#ItemIDSelect").append('<option value="' + erplist[i] + '">' + erplist[i] + '</option>');
}
});
Python web.py代码
#!/usr/bin/python
# _*_ encoding: utf-8 _*_
import web
import xmlrpclib
import json
urls = (
'/(.+)', 'index',
)
class index:
def GET(self):
#THE FOLLOWING IS A SUCCESFULL QUERY FOR DATA TO AN ERP SERVER
server = '***.***.*.**' #hidden the openerp server for stackoverflow post
username = 'admin' #the user
pwd = 'admin' #the password of the user
dbname = 'demo' #the database
# Get the uid
sock_common = xmlrpclib.ServerProxy ('http://%s:8069/xmlrpc/common'%(server))
uid = sock_common.login(dbname, username, pwd)
#replace localhost with the address of the server
sock = xmlrpclib.ServerProxy('http://%s:8069/xmlrpc/object'%(server))
# Unactive all product with a stock = 0.0 and using the ancient code
ids = sock.execute(dbname, uid, pwd, 'res.partner', 'search', [])
p_ids = sock.execute(dbname, uid, pwd, 'res.partner', 'read', ids, ['name'])
#END OF THAT PARTICULAR QUERY
a=[]
for p in p_ids:
a.append(p['name'])
b = json.dumps(a)
return 'some_function(' + b + ')
示例: b
的典型内容["The Jackson Group's Project", "Research & Development", "E-Learning Integration", "Website Design Templates", "Data Import/Export Plugin", "1", "Project XXX", "Contract Agrolait", "Project : Agrolait"]
有人可以帮忙吗?据我所知,有一种方法可以在javascript方面设置函数的名称,所以也许这将是解决它的一种方法,将其设置为some_function我的意思。但是所有关于如何解决这个问题的想法和方法都是受欢迎的,到目前为止我没有尝试过任何工作&gt;。&lt;
感谢阅读!
答案 0 :(得分:2)
JQuery似乎在callback
查询参数中提供了回调函数名称。并确保设置正确的内容类型标题。
callback_name = web.input(callback='callback').callback
web.header('Content-Type', 'application/javascript')
return '%s(%s)' % (callback_name, b)