我在php中编写REST apis而不使用任何框架。我可以使用字符串数据作为参数调用apis,但是当我使用JSON对象作为参数调用url时会出现问题。
- 我的.htaccess文件如下:
# Turn rewrite engine on
Options +FollowSymlinks
RewriteEngine on
# map neat URL to internal URL
RewriteRule ^get/([a-z0-9\-]+)/$ RestController.php?box=$1 [nc,qsa]
RewriteRule ^addinbox/([a-z0-9\-]+)/$ RestController.php?emailObj=$1&mode=addinbox [nc,qsa]
我正在使用jQuery进行ajax调用:
-ajax电话:
var emailObj = {
"name": "Mathew Murddock",
"receiver": receiver,
"sender": "daredevil@marvel.com",
"subject": subject,
"content": body,
"time_stamp": time_stamp
};
var objToSend = JSON.stringify(emailObj);
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: "http://localhost/emailServer/addinbox/",
dataType: 'json',
data: objToSend+'/',
success: function(response){
console.log(response);
}
});
但是会返回此错误:
XMLHttpRequest cannot load http://localhost/emailServer/addinbox/?{%22name%22:%22Mathew%20Murddock%22,…%22This%20is%20%20some%20dummy%20text.%22,%22time_stamp%22:%2212:35:0%22}/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
虽然我在服务器端允许交叉来源: -RestController.php
<?php
header('Access-Control-Allow-Origin: *');
//Remaining code
我在ajax调用时获得的URL是:
http://localhost/emailServer/addinbox/?{%22name%22:%22Mathew%20Murddock%22,%22sender%22:%22daredevil@marvel.com%22,%22subject%22:%22This%20is%20a%20mail%22,%22content%22:%22This%20is%20%20some%20dummy%20text.%22,%22time_stamp%22:%2212:35:0%22}/
我是否以错误的方式重写了网址?
答案 0 :(得分:1)
([a-z0-9 - ] +)匹配小写字母,数字和&#34; - &#34;没有其他所以你不会匹配你的json,也考虑停止发送json得到所有。这是一个不好的做法 为了给你打电话,你向我们展示了你的api实际上需要一个POST
答案 1 :(得分:0)
我认为您不需要使用JSON.stringify(emailObj);
contentType: 'application/json; charset=utf-8'
// this line says you need to send json file but you are sending stirng file
我认为你根本不需要在这里使用JSON.stringify或json_decode。只是做:
data : {
"name": "Mathew Murddock",
"receiver": receiver,
"sender": "daredevil@marvel.com",
"subject": subject,
"content": body,
"time_stamp": time_stamp
},
并在php中
$name=$_POST['name'];
请告诉我,如果不适合你?