weixin_33735077 2017-04-24 11:27 采纳率: 0%
浏览 60

Ajax PHP调用不起作用

I tried to run the code below but it doesn't work, and I tried everything I remember and couldn't get to work.

AJAX Call

var status = $(this).prop("checked");
var room_id = id;
$.post('maintenanceControl.php', {action: status, id: room_id});

PHP Script

<?php

if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
    $action = $_POST['action'];
    $id = $_POST['id'];
    if ($action) {
        return manageMaintenance($id, true);
    } else {
        return manageMaintenance($id, false);
    }
}

function manageMaintenance($room_id, $status)
{
    $jsonString = file_get_contents('status.json');
    $data = json_decode($jsonString, true);

    foreach ($data['rooms'] as $key => $entry) {
        if ($key == $room_id) {
            $data[$key]['maintenance'] = $status;
        }
    }

    $newJsonString = json_encode($data);
    file_put_contents('status.json', $newJsonString);

    return true;
}

At first I thought it was a malfunction but the example below worked just fine

$.post( "test.php", function( data ) {
    alert(data);
});

PHP

<?php
echo "test";
  • 写回答

2条回答 默认 最新

  • weixin_33719619 2017-04-24 11:34
    关注

    In order to get data back into the Javascript ajax call, you need the php script to echo something.

    Return values in php do not find their way back into the Ajax call.

    Often, php scripts echo a value, either a single value or if you want the get more complex data from php back into the Ajax call, you can json encode several values and echo that.

    评论

报告相同问题?