1

PythonサーバーとWebブラウザーの間でjsonpを使用してデータを交換しようとしています。クライアント側は次のようになり (jQuery を使用)、問題なく動作します。

$(document).ready(function(){

    $.getJSON('http://127.0.0.1:8888/url/here?callback=?', {
      key: 'value',
      otherKey: 'otherValue'
    }, function(data){
         // Handles the callback when the data returns
          // $.each( data.items, function( antwort, item ) {
          // $("div.test").text(item.text);
          // })
          $("div.test").text('Success');
          console.log( data );
          $("div.test").text(data.antwort);
          // $.each(synval.terms, function(tkey, tval){
          //      $("div.test").text(tval.term);
    });

});

最初の init 行の後、python サーバー ソケットは次のような文字列に到達します。

GET /url/here?callback=jQuery111306895637936108335_1435907413063&key=value&otherKey=otherValue&_=143

今、私はこのような文字列を返したいと思います(「それはテストです」を含む「返信」で:

    if data.find("jQuery") <> -1:
        json_header = data[data.find("jQuery"): data.find("&")]
        reply = json_header + "({\"reply\": \"that is a test\"})\n"  
        conn.send(reply)

通信には、現在単純なソケットを使用しています。しかし、それはあまりうまくいきません。もう少し高レベルのソリューションを探しました。そのため、今は BaseHTTPServer を使用し、代わりに do_GET(self) をサブクラス化したいと考えています。しかし、上記のコミュニケーションを実現する方法がわかりません。誰でも助けることができますか?

4

1 に答える 1

1

私はちょうど解決策を見つけました。self.path を使用してリクエスト パラメータを取得し、self.request.sendall() を使用して応答できます。コードは次のとおりです。

#handle GET command
def do_GET(self):
    if format == 'json':  
        print "Anfrage erhalten "
        print self.path
        print json.dumps({'antwort':'das ist ein Test'})

        data=self.path
        json_header = data[data.find("jQuery"): data.find("&")]
        reply = json_header + "({\"antwort\": \"das ist ein Test\"})\n"  
        print (reply)
        self.request.sendall(reply)
于 2015-08-14T17:43:04.927 に答える