我不能爲我的生活弄清楚這裏發生了什麼。我會打開一個不同的瀏覽器來檢查我是否改變了作品,也許我的其他瀏覽器緩存了一些東西,它會起作用!但是,我再次這樣做,似乎並沒有。我要瘋了。AJAX不會觸發PHP腳本
在我的網站syllableapp.com上,我創建了一個可連接到的MySQL數據庫。我做了一個連接到它的PHP腳本,添加了一個簡單的條目,並完成。它被稱爲register_email.php
,它可以訪問here。通過該URL手動訪問它將添加條目。其代碼如下:
<?php
$db = new mysqli("localhost", "username", "password", "table");
if ($db->connect_error) {
echo "Could not connect to database.";
exit;
}
else {
$db->query("INSERT INTO emails (email) VALUES ('weird')");
echo 1;
}
?>
如果我檢查,它會被添加。
但是,我希望它從表單中添加。我在http://syllableapp.com/test/index.html一個HTML文件,看起來像這樣:
<html>
<head>
<title>Syllable - iPhone Speed Reader</title>
<link rel="stylesheet" href="styles/style.css">
<script type="text/javascript" src="scripts/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.23.min.js"></script>
</head>
<body>
<div class="content">
<img src="images/app-icon.png" alt="App icon">
<h1>Syllable</h1>
<p>Speed reading app for iPhone. Devour all your Instapaper and Pocket articles, and learn to read much faster in the process.</p>
<form method="post" action="">
<input type="email" class="email" placeholder="Email me when it's live">
<input type="submit" class="submit" value="Send">
</form>
<a href="http://twitter.com/syllableapp"></a>
</div>
</body>
</html>
因此,當用戶提交表單,我掛在頂部攔截提交按鈕按下的JavaScript文件,並調用一個AJAX功能提交到PHP表單。 jQuery的的,看起來像:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var email = $.trim($('.email').val());
var emailRegEx = /^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/;
if (email == "" || !emailRegEx.test(email)) {
event.preventDefault();
$(this).effect("shake", { times:2 }, 75);
}
else {
$.ajax({
type: "POST",
url: "http://syllableapp.com/test/register_email.php",
data: { "message": "hi" },
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
});
});
這基本上只檢查它是否是一個有效的電子郵件地址,然後如果是這樣,調用PHP文件。
但是,每次我點擊提交,它說失敗。這究竟爲何發生?爲什麼我可以直接訪問它,但它不會讓我使用AJAX?
你有任何的PHP日誌? – Lance
請原諒我的無知,但我該如何抓住這些? –
查找名爲error_log的文件,您是否曾嘗試在anon click函數的開頭添加e.preventDefault()?並傳遞給函數。 –