2016-09-06 252 views
0

我無法使用jquery發送POST/Get請求。我有一個python Flask服務器設置。捲曲要求完美。我可以看到請求觸發服務器,但這些Ajax請求不會觸及服務器。以下是我一直在努力的代碼。JQuery .ajax不發送請求

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <meta name="viewport" content="width=device-width"> 
     <title>JS Bin</title> 
     <script src="https://code.jquery.com/jquery-1.9.1.js"></script> 
     <script> 
     $(document).ready(function() { 

     $("#b1").click(function() { 
      $.ajax({ 
       type: 'post', 
       url: 'http://np.mystiq.xyz/paste', 
       complete: function(response) { 
        $('#output').html(response.responseText); 
       }, 
       error: function() { 
        $('#output').html('Bummer: there was an error!'); 
       }, 
      }); 
     }); 
    }); 

    </script> 
    </head> 
    <body> 
    <button id="b1">test success </button> 
    <div id="output"/> 
    </body> 
</html> 

但這小提琴似乎工作http://jsfiddle.net/zc59uLnc/所以,問題是用jQuery。不知道究竟是什麼問題。任何幫助深表感謝。

+0

它是停留在跨域?如果您從同一個域名申請,該怎麼辦? 如果是跨域,請將'Access-Control-Allow-Origin'設置爲'*' 請參閱http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain – vee

回答

0

更改錯誤:

error: function(xhr, textStatus, error){ 
    $('#output').html('Bummer: there was an error! Check the console for details.'); 
    console.log(xhr.statusText); 
    console.log(textStatus); 
    console.log(error); 
} 

它應該指向你的解決方案。

+0

此http:// jsfiddle.net/zc59uLnc/似乎工作,但我的HTML張貼不起作用:( – deeshank

+0

添加我的代碼。控制檯說什麼? – GAEfan

+0

控制檯顯示jquery的代碼,看起來像它沒有拋出錯誤。 /jsbin.com/jezeqavime/edit?html,console,output – deeshank

0

您確定您的視圖接受POST HTTP方法嗎?當您使用捲曲時,您是否使用POST或GET進行測試?

下面的代碼對我的作品:

app.py:

from flask import Flask, jsonify, render_template 

app = Flask(__name__) 


@app.route('/', methods=['GET']) 
def index(): 
    return render_template('index.html') 


@app.route('/hello', methods=['POST']) 
def hello(): 
    return jsonify({'test': 'test message'}) 


if __name__ == "__main__": 
    app.run(host="0.0.0.0", debug=True) 

模板/ index.html的,我剛剛粘貼您的模板,改變您的網址:

url: 'http://my_vm_ip:5000/hello' 

而不是:

url: 'http://np.mystiq.xyz/paste' 

如果你有一些跨域問題,將下面的代碼添加到您的app.py文件:

@app.after_request 
def after_request(response): 
    response.headers.add('Access-Control-Allow-Origin', '*') 
    response.headers.add('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') 
    response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS') 
    return response 
+0

是的,它接受POST和curl -X POST'np.mystiq.xyz/paste'正常,但通過ajax失敗 – deeshank

+0

你試過C在我的答案ö片段?當你加載你的頁面時你得到的錯誤是什麼? (你可以檢查你的鉻控制檯看到生成的錯誤) – ettanany

+0

有沒有錯誤..我沒有嘗試的代碼段..但沒有幫助..我不知道如果你檢查我編輯的帖子.. http:// jsfiddle.net/zc59uLnc/的作品,但沒有在我的代碼.. – deeshank