2015-12-05 82 views
0

我有這個問題。AJAX + php + html - php不創建文件

我運行一個HTML與AJAX:

<html> 
<head> 
<script> 
function ajax_post(){ 
    // Create our XMLHttpRequest object 
    var hr = new XMLHttpRequest(); 
    // Create some variables we need to send to our PHP file 
    var url = "my_parse_file.php"; 
    var fn = document.getElementById("first_name").value; 
    var ln = document.getElementById("last_name").value; 
    var vars = "firstname="+fn+"&lastname="+ln; 
    hr.open("POST", url, true); 
    // Set content type header information for sending url encoded variables in the request 
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    // Access the onreadystatechange event for the XMLHttpRequest object 
    hr.onreadystatechange = function() { 
     if(hr.readyState == 4 && hr.status == 200) { 
<------> var return_data = hr.responseText; 
<------> document.getElementById("status").innerHTML = return_data; 
     } 
    } 
    // Send the data to PHP now... and wait for response to update the status div 
    hr.send(vars); // Actually execute the request 
    document.getElementById("status").innerHTML = "processing..."; 
} 
</script> 
</head> 
<body> 
<h2>Ajax Post to PHP and Get Return Data</h2> 
First Name: <input id="first_name" name="first_name" type="text"> <br><br> 
Last Name: <input id="last_name" name="last_name" type="text"> <br><br> 
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br> 
<div id="status"></div> 
</body> 
</html> 

(這不是我的代碼是這樣,但是從這裏:https://www.developphp.com/video/JavaScript/Ajax-Post-to-PHP-File-XMLHttpRequest-Object-Return-Data-Tutorial

它要求服務器端PHP,那就是:

<?php 
echo "hi"; 
$file = 'people.txt'; 
file_put_contents($file, "hello", FILE_APPEND | LOCK_EX); 
?> 

如果我點擊HTML按鈕它給後面的「喜」到屏幕上,所以我假定HTML,AJAX,PHP連接工作正常,但文件「people.txt」沒有按」 t顯示在服務器端。

我想這肯定是一些許可問題,但我無法弄清楚! PLS幫助! 謝謝!

回答

0

這是一個簡單的,但令人沮喪的。 我需要

chmod 777 

不只是PHP文件,但文本文件也是如此。 現在它的工作!

+0

請注意,PHP文件本身並不需要有777文件權限 –

+0

哦,我明白了!謝謝! –

0

試試這個:

<?php 
    echo "hi"; 
    $file = 'people.txt'; // You shoud have this file in the directory where your my_parse_file.php is 
    // Open the file to get existing content 
    $current = file_get_contents($file); 
    // var_dump($current); exit; // Uncomment this, if you have a error 
    // Append a new data to the file 
    $current .= "hello\n"; 
    // Write the contents back to the file 
    file_put_contents($file, $current); 
?> 

或者你可以試試這個:

<?php 
    function file_force_contents($filename, $data, $flags = 0){ 
     if(!is_dir(dirname($filename))){ 
      mkdir(dirname($filename).'/', 0777, TRUE); 
     } 
     return file_put_contents($filename, $data,$flags); 
    } 
    $file = 'people.txt'; 
    file_force_contents($file,'test1 content'); // test1.txt created 
    echo 'Success'; 
?> 
+0

謝謝,它也沒有工作,雖然它可能比我的代碼更好。不過剛剛在另一個論壇上發現了這個問題。我補充說,作爲我原來的問題的答案! 感謝您的努力! –