AJAX发布到数据库 [英] AJAX post to database

查看:72
本文介绍了AJAX发布到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过其他问题,但找不到答案为什么不起作用.我正在在线学习教程.这是我的代码:

I have looked at other questions and cannot find the answer to why this isn't working. I am following a tutorial online. Here is my code:

HTML文件:

<!DOCTYPE HTML>
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<h4>Enter an Item</h4>
<input type="text" id="item" /><br />
<input type="button" id="button" value="Submit" /><br />
<div id="content"></div>
<script type="text/javascript" scr="ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
</body>
</html>

JS文件:

$('#button').click(function() {
var item = $('#item').val();

$('#content').text('Loading...');

$.post('ajax.php', { item: item }, function(data) {
    $('#content').text(data);
    });
});

PHP文件:

<?php
include 'db.php';

if (isset($_POST['item'])) {
    $item = $_POST['item'];
    $sql = mysql_query("INSERT INTO items(item)VALUES('$item')");
    if ($sql === true) {
        echo "Inserted into database";
    } elseif ($sql ==== false) {
        echo "Error inserting into database";
    }
 }
 ?>

我看不到我在做什么错.本教程具有相同的代码.感谢您的帮助.

I don't see what I'm doing wrong. The tutorial has the same code. Thanks for your help.

推荐答案

moonwave99是正确的(我不确定为什么要投票).而且在您的html中,scr ="ajax"也应为src ="ajax"并且应该放在头脑中,甚至之前.其他原因可能是ajax.php在网站上的位置,也许声明整个URL会有所帮助:

moonwave99 is right (I'm not sure why the downvotes).. and also the scr="ajax" should be src="ajax" in your html and should be put in head or even before. Other reason may be the position of ajax.php to the site, maybe declaring whole URL will help :

$.post('http://wholeurl/ajax.php', { 
      item: item 
   }, function(data) {
      $('#content').text(data);
   });

希望这会有所帮助,如果没有帮助,请指定错误.

Hope this helps, if not please specify error.

这篇关于AJAX发布到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆