1

所以我试图让一个基于 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。但是所有关于如何解决这个问题的想法/方法都是欢迎的,到目前为止我没有尝试过任何工作>。<

谢谢阅读!

4

1 回答 1

2

JQuery 似乎在callback查询参数中提供回调函数名称。并确保设置正确的内容类型标头。

callback_name = web.input(callback='callback').callback
web.header('Content-Type', 'application/javascript') 
return '%s(%s)' % (callback_name, b)
于 2013-10-06T19:35:03.510 回答