将字符串从js传递到php

I'm a complete beginner at javascript & php. I'm trying to pass a variable from javascript to php using ajax. I looked at some of the other posts on this topic and tried to copy the syntax, but something's still not working. Here's a copy of the relevant part of the code (note: I commented out the parts that differ):

This works: PHP:

<?php
// Reads in tab-delimited file and outputs json file
$csv = file_get_contents("status.txt")
//$csv = $_POST['csv'];
function csvToJson($csv) {
    $rows = explode("
", trim($csv));
    $data = array_slice($rows, 1);
    $keys = array_fill(0, count($data), $rows[0]);
    $json = array_map(function ($row, $key) {
        return array_combine(str_getcsv($key), str_getcsv($row));
    }, $data, $keys);

    return json_encode($json);
}

$json = csvToJson($csv);
return $json;
?>

JS:

function initialize() {
// Create data variables, calling .ajax to convert tab-delimited to csv file
//    var csv = file_get_contents("status.txt");
    var status = $.ajax({
//      type: "POST",
        url: "statusgetJson.php",
//      data: {"csv": csv},
        dataType:"json",
        async: false
    }).responseText;

This doesn't work: PHP:

<?php
// Reads in tab-delimited file and outputs json file
//$csv = file_get_contents("status.txt")
$csv = $_POST['csv'];
function csvToJson($csv) {
    $rows = explode("
", trim($csv));
    $data = array_slice($rows, 1);
    $keys = array_fill(0, count($data), $rows[0]);
    $json = array_map(function ($row, $key) {
        return array_combine(str_getcsv($key), str_getcsv($row));
    }, $data, $keys);

    return json_encode($json);
}

$json = csvToJson($csv);
return $json;
?>

JS:

function initialize() {
// Create data variables, calling .ajax to convert tab-delimited to csv file
    var csv = file_get_contents("status.txt");
    var status = $.ajax({
        type: "POST",
        url: "statusgetJson.php",
        data: {"csv": csv},
        dataType:"json",
        async: false
    }).responseText;

The error I get is: "Uncaught ReferenceError: file_get_contents is not defined". What am I doing wrong?

查看全部
weixin_33739523
weixin_33739523
2015/03/22 20:08
  • php
  • ajax
  • javascript
  • jquery
  • 点赞
  • 收藏
  • 回答
    私信

0个回复