没有查询字符串的Ajax rest请求url

时间:2017-06-14 12:00:38

标签: jquery python ajax rest

我有一个简单的烧瓶 - restful api,我喜欢做一个ajax请求来检索一些数据。但是ajax请求包含数据作为查询字符串,这使得url对api无效。以下是代码:

烧瓶 - 安抚api:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

articles = {"1001":"article1001"}

class Stock(Resource):
    def get(self, article_number):
        return {article_number: articles[article_number]}

api.add_resource(Stock, '/stock/<string:article_number>')

ajax调用是:

var arg = '1001'
function testApiGet(arg){
  $.ajax({
    type: "GET",
    data: {article_number: arg},
    url:'http://127.0.0.1:5000/stock',
    success: function(data){
      console.log("API works fine")
    }
  })
}

查看localhost服务器的日志,ajax尝试请求以下URL:

"GET /stock?article_number=1001 HTTP/1.1" 404 -

虽然我想要实现的是从ajax到此url的请求:

"GET /stock/1001"

我已经尝试将ajax请求更改为此,但它确实有效,但我觉得这不是正确的技术。

function testApiGet(arg){
  $.ajax({
    type: "GET",
    // I add arg to the url as a normal string.
    url:'http://127.0.0.1:5000/stock/'+arg, 
    success: function(data){
      console.log("API works fine")
    }
  })
}

2 个答案:

答案 0 :(得分:0)

我认为这是一种干净的方式,但由于你手头有jQuery,你可以简化:

var arg = '1001'
function testApiGet(arg){    
  $.get('http://127.0.0.1:5000/stock/'+ arg, function( data ) {
    console.log("API works fine")
  });
}

为了更好的衡量,请使用.done.fail.always:

var arg = '1001'
function testApiGet(arg){    
  $.get('http://127.0.0.1:5000/stock/'+ arg)
  .done(function() {
    console.log("API works fine");
  })
  .fail(function() {
    console.log("API DOESN'T work fine");
  })
  .always(function() {
    console.log( "Do this no matter what works or not." );
  });
}

答案 1 :(得分:0)

使用:

dataType: 'json'

它将与GET请求一起使用,而无需获取404即可处理查询字符串。

var arg = '1001'
function testApiGet(arg){
  $.ajax({
    type: "GET",
    dataType: 'json',
    data: {article_number: arg},
    url:'http://127.0.0.1:5000/stock',
    success: function(data){
      console.log("API works fine")
    }
  })
}