Jquery 为什么我在MongoDB REST API中得到一个字符串错误的请求?
我正在从事一个与任务规划有关的项目,目前我似乎遇到的唯一问题是,当我使用MongoLab的RESTAPI进行调用时 如果文本中有一个Jquery 为什么我在MongoDB REST API中得到一个字符串错误的请求?,jquery,mongodb,rest,Jquery,Mongodb,Rest,我正在从事一个与任务规划有关的项目,目前我似乎遇到的唯一问题是,当我使用MongoLab的RESTAPI进行调用时 如果文本中有一个%,它会作为一个错误的请求返回,如果我将文档中的名称更改为没有%,然后在变量中没有%的情况下再次运行它,它不会有问题,但问题是resultName是动态的,对许多用户来说都是动态的,并且会有许多结果,并且可能会有人的结果“体重减少10%” 我使用的代码如下: resultName = "Reduce everything by 10%"; urlTest = 'ht
%
,它会作为一个错误的请求返回,如果我将文档中的名称更改为没有%,然后在变量中没有%的情况下再次运行它,它不会有问题,但问题是resultName
是动态的,对许多用户来说都是动态的,并且会有许多结果,并且可能会有人的结果“体重减少10%”
我使用的代码如下:
resultName = "Reduce everything by 10%";
urlTest = 'https://api.mongolab.com/api/1/databases/myDB/collections/users/?apiKey=myAPIKey&q={"result_name":"' + resultName + '"}';
$.ajax(
{ url: urlTest,
type: "GET",
contentType: "application/json",
async: false
}
).success(function(returnedData) {
console.log(returnedData);
});
我如何仍然允许使用其他代码的<代码> %<代码>符号,仍然没有正确的请求而拉正确的数据?
您可能首先考虑通过使用原生JavaScript函数来逃避<代码> %>代码>字符,然后使用<强> < /强>函数对API RestulyGET实现进行解码。n 一些测试证明了这一点:var resultName = "Reduce everything by 10%";
resultName = encodeURI(resultName);
decodedResultName = decodeURI(resultName);
urlTest = 'https://api.mongolab.com/api/1/databases/myDB/collections/users/?apiKey=myAPIKey&q={"result_name":"' + resultName + '"}';
console.log(resultName);
console.log(decodedResultName);
console.log(urlTest);
输出日志:
Reduce%20everything%20by%2010%25
Reduce everything by 10%
https://api.mongolab.com/api/1/databases/myDB/collections/users/?apiKey=myAPIKey&q={"result_name":"Reduce%20everything%20by%2010%25"}
因此,您可以使用函数在后端解码查询对象字符串:
db.test.insert([
{ "result_name": "Decrease Bodyweight by 10%" },
{ "result_name": "Reduce everything by 10%" }
])
var q = {"result_name":"Reduce%20everything%20by%2010%25"};
q.result_name = decodeURI(q.result_name);
db.test.find(q);
给出:
/* 0 */
{
"_id" : ObjectId("5549f951180e849972939049"),
"result_name" : "Reduce everything by 10%"
}
Nicholas,你进展如何?下面有一个答案等着你。encodeURI和decodeURI对我有效。db.test.insert的示例代码不适用于我,因为我目前正在对mongodb进行AJAX调用。@NicholasDarley感谢你的反馈,很高兴这对你有效。