Ajax is submitted by default in application/x-www-form-urlencoded mode. This is the common form submission method. Using the $_post method in PHP is easy to get.
However, if you force the AJAX request header to be Application/json, your $_post will not be accepted. It must be taken out using $globals[' Http_raw_post_data ') and then json_decode on the line.
such as fetch, Axios the default request header is Application/json, so pay attention.
There are some details you need to know.
1. The backend must allow the front end to define header requests such as Content-type.
Header (' Access-control-allow-headers:x-requested-with,content-type '
2. The output of exit in PHP only allows strings. So it's best to use (string) to escape what you want to output.
3, if using the Ajax Application/json way, remember that the data parameter is a string type. Use Json.stringify () to convert.
jquery Ajax Code:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Document</title> <Scriptsrc= "Https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></Script></Head><Body> <Script> $(function() {$.ajax ({type:"Post", URL:"http://localhost:8080/news.php", Data:JSON.stringify ({newsid:101}), headers: {"Content-type": "Application/json; Charset=utf-8"}, Success:function(data) {Console.log (data)}}) }) </Script></Body></HTML>
PHP Code:
<? PHP Header ("access-control-allow-origin:*"header(' Access-control-allow-headers:x-requested-with, Content-type '$rws _post$GLOBALS[' Http_raw_post_data ']; $mypost = Json_decode ($rws _post); $newsid = (string)$mypost,NewSID; Exit ($newsid);
PHP content-type for "Application/json" post data $_post not accept the problem