无法通过 ajax 将字符串参数传递给 php 函数


Unable to pass string parameter to php function via ajax

我正在对codeigniter php函数进行以下jquery ajax调用:

    $.ajax({
                        type:"POST",
                        url: "Ajax/getHtml",
                        data: { u : 'http://stackoverflow.com/' },
                        contentType: "application/json; charset=utf-8",
                        dataType: 'html',       
                        success: function(data) {
                            console.log(data);
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                                console.log('error');
                                console.log(jqXHR,textStatus, errorThrown);
                        }
                    });

请求的 php 函数是:

public function getHtml() {
        var_dump($_POST);
        $url = $_POST['u'];
        $result = file_get_contents($url);
        echo ($result);
}

var_dump($_POST)收益率:

array(0) { }

我该如何解决这个问题?

如果请求的内容类型为 application/json; charset=utf-8,Php 将不会填充 $_POST 数组,您也不会发送 json。 只需删除内容类型行,即可设置正确的(默认)内容类型application/x-www-form-urlencoded