2013-09-05 50 views
1

因此,我試圖讓一個基於web.py的python webservice在jQuery對它進行ajax調用後通過JSONP發回列表對象。如何讓web.py python webservice返回一個jsonp調用jquery

問題是讀了很多的例子,我仍然無法理解如何使它工作後。下面是我得到了我與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。但是,如何解決這個問題的所有想法/方法都是受歡迎的,迄今爲止我沒有嘗試過>。 <

感謝您的閱讀!

回答

2

JQuery的似乎在callback查詢參數提供的回調函數的名稱。並確保設置正確的內容類型標題。

callback_name = web.input(callback='callback').callback 
web.header('Content-Type', 'application/javascript') 
return '%s(%s)' % (callback_name, b) 
+0

非常有益的TY! – MrHappy