2016-09-06 248 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