使用parse api进行复杂的ajax查询

时间:2015-07-23 16:47:24

标签: javascript python api parse-platform

我正在处理parse.com的apis。我想在我的javascript函数中进行复杂的查询。

我无法在ajax get请求的代码下设置等效params部分。任何帮助appriciated。

例如,要检索1000到3000之间的分数,他们在python中给出了示例,

import json,httplib,urllib
connection = httplib.HTTPSConnection('api.parse.com', 443)
params = urllib.urlencode({"where":json.dumps({
       "score": {
         "$gte": 1000,
         "$lte": 3000
       }
     })})
connection.connect()
connection.request('GET', '/1/classes/GameScore?%s' % params, '', {
       "X-Parse-Application-Id": "pcHvGniu2bbGggMofkcVKQUK91g5V3U5g4ZGWifK",
       "X-Parse-REST-API-Key": "5pI5vb7dNu8mRY6yPFTOtpIdpUHeqv5gMChFaQxK"
     })
result = json.loads(connection.getresponse().read())
print result

1 个答案:

答案 0 :(得分:1)

javascript中的代码可以更短:

$.ajax({
        type:"GET",
        beforeSend: function (request)
        {
            request.setRequestHeader("X-Parse-Application-Id", 'pcHvGniu2bbGggMofkcVKQUK91g5V3U5g4ZGWifK');
            request.setRequestHeader("X-Parse-REST-API-Key", '5pI5vb7dNu8mRY6yPFTOtpIdpUHeqv5gMChFaQxK');
        },
        url: "https://api.parse.com/1/classes/GameScore",
        data: "where=" + escape(JSON.stringify({"score": {"$gte": 1000, "$lte": 3000 }})),
        processData: false,
        success: function(msg) {
            console.log(JSON.parse(msg));
        }
});

JQuery会将数据附加到url作为查询字符串,最终请求URL将为:

https://api.parse.com//1/classes/GameScore?where=%7B%22score%22%3A%7B%22%24gte%22%3A1000%2C%22%24lte%22%3A3000%7D%7D

当然,自己构建网址是可以的:

var url = "https://api.parse.com/1/classes/GameScore?where=" + escape(JSON.stringify({"score": {"$gte": 1000, "$lte": 3000 }}))
$.ajax({
    type:"GET",
    beforeSend: function (request)
    {
        request.setRequestHeader("X-Parse-Application-Id", 'pcHvGniu2bbGggMofkcVKQUK91g5V3U5g4ZGWifK');
        request.setRequestHeader("X-Parse-REST-API-Key", '5pI5vb7dNu8mRY6yPFTOtpIdpUHeqv5gMChFaQxK');
    },
    url: url,
    processData: false,
    success: function(msg) {
        console.log(JSON.parse(msg));
    }

});

请求网址与上一个网址相同。