【问题标题】:JQuery .ajax not sending requestJQuery .ajax 不发送请求
【发布时间】:2017-01-14 11:41:03
【问题描述】:

我无法使用 jquery 发送 POST/Get 请求。我有一个 python Flask 服务器设置。卷曲请求完美地工作。我可以看到请求到达服务器,但这些 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 上。不确定到底是什么问题。非常感谢任何帮助。

【问题讨论】:

标签: jquery html ajax post


【解决方案1】:

将错误改为:

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);
}

它应该为您指出解决方案。

【讨论】:

【解决方案2】:

您确定您的视图接受 POST HTTP 方法吗?你在使用 curl 时是否使用 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)

templates/index.html 中,我只是粘贴了您的模板并将您的 url 更改为:

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

【讨论】:

  • 是的,它接受 POST 和 curl -X POST 'np.mystiq.xyz/paste' 工作正常,但通过 ajax 失败
  • 您在我的回答中尝试过代码 sn-p 吗?加载页面时遇到的错误是什么? (您可以检查您的 chrome 控制台以查看生成的错误)
  • 没有错误.. 我确实尝试了 sn-p.. 但没有帮助.. 我不确定你是否检查了我编辑的帖子.. jsfiddle.net/zc59uLnc 有效但不在我的代码..
  • 你确定你检查过你的 chrome 控制台没有收到任何错误吗?请使用 F12 或 Ctrl+Shift+I(在 PC 上)并确保控制台选项卡上没有显示任何内容。此外,单击“网络”选项卡,查看单击“测试成功”按钮时是否发送了请求。对我来说,当我点击那个按钮时,我得到了正确的结果。
猜你喜欢
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 2016-07-25
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多