在php文件中使用post方法的变量

时间:2018-05-09 08:53:09

标签: php post

我目前有2个文件:

  • movie.php
  • deletemovie.php

movie.php将有一个javascript函数deletemovie(movietitle)

单击某个项目时会触发该功能。

<button class='btn btn-danger' onclick = deletemovie('{$movie['title']}')>X</button>

deletemovie(movietitle)是:

function deletemovie(movietitle){
    console.log(movietitle);
    $.post("deletemovie.php", movietitle, "json");
  }

我的问题是,当我在deletemovie.php中处理发布数据时,

$title = $_POST[movietitle];
foreach ($movies as $movie){
    if ($movie['title'] == movietitle) {
        unset($movie['title']);
    } 
}
我应该这样写吗? 我认为$title = $_POST[movietitle];在某种程度上是错误的。

有什么建议吗?

我目前的代码是:

  

movie.php

function deletemovie(movietitle){
  console.log(movietitle);
  $.post("deletemovie.php", movietitle, "json");
}
  

deletemovie.php

foreach ($movies as $movie){
if ($movie['title'] == $_POST['movietitle']) {
    unset($movie['title']);
}
}

我认为unset()没有错? 但问题仍未解决。

movie.json:

{
    "abc": {
        "title": "abc",
        "director": "ddd",
        "rating": "5",
        "subtitle": "Yes",
        "genre": "I",
        "category": "I",
        "release": "2018-05-03",
        "end": "2018-05-09",
        "link": "das",
        "synopsis": "dasdas"
    },
    "afs": {
        "title": "afs",
        "director": "fasf",
        "rating": "5",
        "subtitle": "Yes",
        "genre": "I",
        "category": "I",
        "release": "2018-05-09",
        "end": "2018-05-10",
        "link": "fsa",
        "synopsis": "fs"
    }
}

3 个答案:

答案 0 :(得分:2)

您是否尝试将“movietitle”放入撇号?

$title = $_POST['movietitle'];

否则php可能会将movietitle解释为未知常量而无法找到任何内容。

此外,这条线看起来很错误:

if ($movie['title'] == movietitle)

你可能想要:

if ($movie['title'] == $_POST['movietitle'])

答案 1 :(得分:0)

你应该在apostophes

中写下movietitle
$title = $_POST['movietitle'];    

答案 2 :(得分:0)

将你的json转换为php数组,如下所示:

$php_array = json_decode($json_value, true);

$php_array内容:

[
   "abc" => [
        "title"=>"abc",
        "director"=>"ddd",
        "rating"=>"5",
        "subtitle"=>"Yes",
        "genre"=>"I",
        "category"=>"I",
        "release"=>"2018-05-03",
        "end"=>"2018-05-09",
        "link"=>"das",
        "synopsis"=>"dasdas"
    ],
    "afs" => [
        "title"=>"afs",
        "director"=>"fasf",
        "rating"=>"5",
        "subtitle"=>"Yes",
        "genre"=>"I",
        "category"=>"I",
        "release"=>"2018-05-09",
        "end"=>"2018-05-10",
        "link"=>"fsa",
        "synopsis"=>"fs"
    ]
]

然后取消设置发布的电影:

foreach($php_array as $movie=>$details){
   if($details['title'] == $_POST['movietitle']){
      unset($php_array[$movie]);
   }
}

将结果转换为json:

$json_output = json_encode($php_array);

现在,$json_output的内容是json格式中没有$_POST['movietitle']的电影列表。