我试图恢复在Open311中注册的一些投诉,其中包含字符串" Noise"。这是我的网址构建器:
var start_date = formattedDate(startDate)+"T00:00:00"; //YYYY-MM-DD
var end_date = formattedDate(endDate)+"T23:59:59"; //YYYY-MM-DD
var c_type = 'Noise'; // Complaint Type
// Build the data URL
URL = "http://data.cityofnewyork.us/resource/erm2-nwe9.json"; // API Access Endpoint
URL += "?"; // A query parameter name is preceded by the question mark
URL += "$where="; // Filters to be applied
URL += "(latitude IS NOT NULL)"; // Only return records with coordinates
URL += " AND ";
URL += "(complaint_type like '\\%" + c_type + "\\%')";
URL += " AND ";
URL += "(created_date>='" + start_date + "') AND (created_date<='" + end_date + "')"; // Date range
URL += "&$group=complaint_type,descriptor,latitude,longitude"; // Fields to group by
URL += "&$select=descriptor,latitude,longitude,complaint_type"; // Fields to return
URL = encodeURI(URL); // Encode special characters such as spaces and quotes
URL = URL.replace("'%5C%25", "%27\\%"); // Only way that seems to work in this project
URL = URL.replace("%5C%25'", "\\%%27");
测试的编码网址:
但是,此链接包含大量不相关的投诉,其中提交的 complaint_type 不包含世界&#34;噪音&#34;。
为什么?我错过了什么吗?
答案 0 :(得分:2)
您正在使用实现协议版本2.0的旧端点,不支持LIKE
。
您应该将端点更改为fhrw-4uyv
,它支持2.1和LIKE。
此外,您的网址构建非常糟糕。您应该创建每个参数的值,并使用encodeURIComponent
单独编码每个参数,然后在URL中将它们合并在一起。您的请求中不应包含任何类似\%
的内容。
URL的错误结构意味着它无法正确解析,$where
可能完全被忽略。
以下是有效请求的示例:
http://data.cityofnewyork.us/resource/fhrw-4uyv.json?$其中=(纬度%图20是%20NOT%20NULL)%20于是%20(complaint_type%20LIKE%20%27%25Noise%25%27)%20于是%20(CREATED_DATE%3E =% 272015-11-01T00:00:00%27)%20于是%20(CREATED_DATE%3C =%272015-12-01T23:59:59%27)及$组= complaint_type,描述符,纬度,经度和安培; $选择=描述符,纬度,经度,complaint_type
注意喜欢的论点是%27%25Noise%25%27
('%Noise%'
)。
更新的代码:
var c_type = "Noise",
start_date = "2013-08-01",
end_date = "2013-08-08";
var condition = "";
condition += "(latitude IS NOT NULL)"; // Only return records with coordinates
condition += " AND ";
condition += "(complaint_type like '%" + c_type + "%')";
condition += " AND ";
condition += "(created_date>='" + start_date + "') AND (created_date<='" + end_date + "')"; // Date range
var URL;
URL = "http://data.cityofnewyork.us/resource/fhrw-4uyv.json"; // API Access Endpoint
URL += "?"; // A query parameter name is preceded by the question mark
URL += "$where="; // Filters to be applied
URL += encodeURIComponent(condition);
URL += "&$group=complaint_type,descriptor,latitude,longitude"; // Fields to group by
URL += "&$select=descriptor,latitude,longitude,complaint_type"; // Fields to return
答案 1 :(得分:1)
查询中看起来不像是错误,端点不支持“LIKE”(文档建议只使用v2.1中的端点。
选择http://data.cityofnewyork.us/resource/erm2-nwe9.json?$where=complaint_type%20like%20%27%27
即使您将查询向下剥离,它仍然无法正常工作。然而,
http://data.cityofnewyork.us/resource/erm2-nwe9.json?$where=complaint_type%20=%20%27%25NOISE%25%27
将LIKE更改为等号将起作用,表明语法本身很好。