繁体   English   中英

使用 Axios 将数据发布到 PHP

[英]Posting Data to PHP with Axios

我正在创建一个 Vue 应用程序,我在其中使用 Axios 发布到 PHP。 所以我所拥有的是:

methods: {
         onSubmit () {
       axios.post('/wp-content/themes/bones/library/jobsResponse.php',{region: Chicago, jobType: Direct Hire}, {headers: {'X-Requested-With': 'XMLHttpRequest', 'Content-type': 'application/x-www-form-urlencoded'}})
       .then(function(response){
         console.log(response)
       })
       .catch(function(error){console.log(error)})
      },

}

该方法的作用是当 onSubmit 函数运行时,它将使用 Axios POST 到我创建的名为 jobsResponse.php 的 PHP 文件。 它发布的数据是“地区:芝加哥地区,工作类型:直接雇用”。

然后在那个jobsResponse.php PHP文件中我有:

<?php
$_POST = json_decode(file_get_contents('php://input'), true);

$region = $_POST['region'];

$jobType = $_POST['jobType'];

echo $region;
echo $jobType;

echo ' this is the posted data content';
?>

这就是使用 Axios 从 Vue 获取发布的数据。 在 Axios 中,我正在运行响应的 console.log,当我检查控制台日志时,它会显示我发布到 jobsResponse.php 的数据在此处输入图片说明

正如您在上图中所看到的,来自我的 Vue 应用程序的数据已发布到 jobsResponse.php 文件中。 所以这一切都很好。 我现在需要做的是获取我发布到 jobsResponse.php 文件的数据并在我的 Vue 应用程序中使用它。

所以目前在我的 Vue 应用程序中,我正在使用 PHP 接收一个 JSON 对象,如下所示:

<?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded,externalCategoryID,employmentType,customText12', null, 200, '-dateAdded');?>

我想要做的是在该 PHP 查询中使用来自 Axios 的发布数据。 所以我需要将发布的数据以某种方式插入到 PHP 中,例如:

<?php echo getBhQuery('search','JobOrder','isOpen:true AND customText12:"'.$region.'"','id,title,categories,dateAdded,externalCategoryID,employmentType,customText12'); ?>

将 $region 变量添加到 PHP 查询将过滤 JSON 对象以仅拉回具有该变量设置的区域的职位发布。

所以我有需要的数据发布,这很好。 我只是不确定如何获取该数据并使用它来动态生成新的 JSON 对象,例如对其进行 ajaxing。

好吧, $_POST _ $_POST是一个超全局变量,所以我不会覆盖它,因为它们由 PHP 自动处理,最好单独处理。

就像提到的评论一样, $post = file_get_contents('php://input') ?? $_POST; $post = file_get_contents('php://input') ?? $_POST; 将接收传入的 POST 请求并将其分配给变量$post 然后一旦你解析它: $post = json_decode($post, true); 这会将 JSON 字符串解析为关联的数组。

然后获取您提到的变量$region$jobType

然后,您可以将这些插入到您的数据库查询中,或者如果您不进行此生产并且可以拥有固定数据:拥有静态文本文件或将作业列表保存到变量中。

// get the incoming POST data
$post = file_get_contents('php://input') ?? $_POST;

// decode the JSON data
$post = json_decode($post, true);

// assign the needed data from the POST object
$region = $post['region'];

$jobType = $post['jobType'];

// define how you want to filter the data
function $sortJobs($job) use ($region, $jobType)
{
  return ($job['region'] == $region) && ($job['type'] == $jobType);
}

// get your jobs data
$jobs = [[ 'type' => 'x', 'region' => 'minneapolis', 'name' => 'developer'], ['type' => 'y', 'region' => 'chicago', 'name' => 'secretary']];

// filter the jobs data
$filteredJobs = array_filter($jobs, "sortJobs");

// return the filtered data
http_response_code(200);
echo json_encode($filteredJobs);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM