AJAX没有重新加载页面

时间:2016-10-16 21:29:03

标签: javascript php ajax datetime

我的任务是使用JavaScript和JSON返回并在浏览器上显示数据。我是AJAX的新手,我无法通过按钮点击来解雇AJAX。主要问题是让AJAX启动。

每次用户输入新数据时,我都会尝试在同一屏幕上加载数据。

PHP代码:

<h2>Submit Recipes</h2>
<form id="addRecipes" name="addRecipes" action="Welcome.php"method="POST">
    <fieldset>
        <legend>Submit Recipes</legend>
        <textarea id="recipesId" name="recipes" rows="6" cols="70"></textarea>
        <br/>
        <input type="button" value="Submit" name="submit" onclick="submitRecipes()"/>
    </fieldset>
</form>
<br/>
<table id="recipesTbl" border="1" >
    <tr>
        <th class="row-datetime" name="datetime">DateTime </th>
        <th class ="row-recipes" name="recipes">  Recipes </th>
    </tr>
</table>

Ajax代码:

function submitRecipes() {

    var recipes = document.getElementById("recipesId").value;   
    if (recipes == null || recipes == "") {
        alert("Please enter the recipes");
        return false;
    }

    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {

        if (request.readyState == 4 && request.status == 200) {

             var text = request.responseText;
             var json = JSON.parse(text);

            var table = document.getElementById("recipesTbl");

            var newRow = table.insertRow(1);

            var newCell = newRow.insertCell(0);
            newCell.innerHTML = json.datetime;

            newCell = newRow.insertCell(1);
            newCell.innerHTML = json.recipes;

        }
    }
    request.open("POST", "SubmitRecipes.php", true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    request.send("recipes=" + recipes);

    document.getElementById("recipesId").value = "";
}

PHP文件片段:

<?php
$recipes= $_POST["recipes"];
date_default_timezone_get('UTC');
$datetime = date("Y-m-d H:i:s");

storeRecipes($recipes, $datetime);

echo ('{ "datetime" : "'. $datetime. '",'.
        '"recipes": "'.recipes .'"}');
?>

1 个答案:

答案 0 :(得分:0)

函数storeRecipes不存在。要使JSON.parse有效,单引号(&#39;)必须双引号(&#34;)必须在里面

例如:

&#13;
&#13;
var string = '{"a": "1", "b": "2"}';
var res = JSON.parse(string);
console.log(res);
&#13;
&#13;
&#13;

使用

<?php

$recipes = $_POST["recipes"];
date_default_timezone_get('UTC');
$datetime = date("Y-m-d H:i:s");

// storeRecipes($recipes, $datetime);

$data = '{"datetime": ' . '"' . $datetime . '",';
$data .= '"recipes": ' . '"' . $recipes . '"}';

echo $data;
?>

(以及<head>部分中的脚本文件)它应该可以工作!