重写url以接受json数据php(请求方法:GET)


Rewrite url for accepting json data php (Request method : GET)

我在php中编写RESTapi,而不使用任何框架。我可以用字符串数据作为参数调用api,但当我用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);
               }
            });

但is返回此错误:

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}/

我是否以错误的方式改写了URL?

([a-z0-9-]+)匹配小写字母、数字和"-",所以您不会匹配json,也可以考虑在get-all-gether中停止发送json。这是一种不好的做法为了服务您向我们展示的调用,您的api实际上应该需要POST

我认为您不需要使用JSON.stringfy(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'];

如果不为你工作,请通知我?