javascript - YTParamAPI 页面返回整个 HTML?

标签 javascript php angularjs

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

相关文章:

php - Mysql查询不求和多条记录,只取第一条记录

angularjs - 我的服务中的数据在我的 Angular Controller 中并不持久

javascript - 在 AngularJS Controller 中使用第三方过滤器

javascript - js中这两种方法表示有什么区别

javascript - 这些这代表什么?

javascript - Puppeteer 评估对于 DOM Node 数组返回未定义

php - 应用 LIMIT 时,带有 INNER JOIN 的 DWL 不起作用

javascript - 如何为引用 SVG 背景制作动画

php - 如何使用 php 循环遍历 mysql 查询

javascript - AngularJs 在重定向到新位置时更改后退按钮位置