PHP content-type for "Application/json" post data $_post not accept the problem

Source: Internet
Author: User
Tags exit in

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.