$http({
url: 'http://myURL.com/api/',
method: "POST",
data: { 'YTParam' : 'test' }
})
.then(function(response) {
console.log(response.data);
},
function(response) { // optional
// failed
}
);
在我的控制台中,我看到整个 html 被打印出来,我期待的值是 $_POST[myParam]
。为什么会发生这种情况?
我的PHP如下
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{
margin: 0;
}
</style>
</head>
<body>
<?php
echo $_POST["YTParam"];
if($_POST["YTParam"])
{
$YTParam = $_POST["YTParam"];
echo $YTParam;
}
?>
</body>
</html>
我确实正确关闭了每个标签,但不知道为什么会出现这个问题。
最佳答案
删除.php文件中的所有html,因为它的作用不是直接在浏览器中打印,而是在服务器端处理数据。
所以,剩下的部分是:
<?php
echo $_POST["YTParam"]; // Will be returned to your JS
if($_POST["YTParam"])
{
$YTParam = $_POST["YTParam"];
echo $YTParam; // Will be returned to your JS
}
?>
您要 echo
的所有内容都将在 JS ajax 调用的 response
中返回。
编辑
您的数据不在 $_POST
数组中,因为您的 Angular JS contentType 默认设置为 application/json
,而 PHP 需要 application/x -www-form-urlencoded
用于 POST 请求。 Quoting from docs :
$httpProvider.defaults.headers.post: (header defaults for POST requests)
Content-Type: application/json
要更改此设置,请在配置中更改此值:
yourApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
}]);
或者在您发送请求时:
$http({
url: 'http://myURL.com/api/',
method: "POST",
headers: {
'Content-Type': "application/x-www-form-urlencoded"
},
data: { 'YTParam' : 'test' }
})
您可以直接将 contentType
设置为属性,但我不能 100% 确定这一点。
关于javascript - YTParamAPI 页面返回整个 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29167351/