我实际上对Ajax和jQuery完全不熟悉,但我正在尝试使用这两种方式为我的网站制作一个订阅按钮。
现在我已经阅读了Ajax和jQuery的大部分文档,并提出了一些代码来实现这一点。
问题是它不起作用,我不能为我的生活看到原因。
我点击订阅按钮,没有任何反应:
subscribe.php脚本没有运行,数据库没有更新,没有显示警报 - 就像我说的......没有任何反应
希望有人可以提供帮助。
到目前为止的代码
jQuery.js(在index.php中加载,用于保存body标签开头的所有其他页面)
<body>
// Load official jQuery-library
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
// Load my own jQuery-script file
<script src="jQuery/jQuery.js"></script>
.
.
.
// Load all pages (videos.php, channel.php,...) as needed
</body>
// Code in my own jQuery.js
$(document).ready(function(){
"use strict";
$("#subscribe").click(function(subscribeData){
$.ajax({
type: "POST",
url:'../scripts/subscribe.php',
data:{randomStringUser:subscribeData},
dataType:'json',
success:function(data){
alert("You subscribed");// Do what you do after subscribe.php has done it's thing
// just to test I just put an alert here
},
error:function(){
alert("Didn't work");// Do what you do if mission failed
// just to test I just put an alert here
}
});
});
});
PHP位于订阅按钮所在页面的顶部(即.fate.php)和订阅按钮代码
<?php
.
.
.
$randomStringUser = $_GET['channel'];
$subscribeData = json_encode($randomStringUser);
?>
// Page html
.
.
.
// Subscribe-button
<button type="button" class="btn btn-success" id="subscribe">
Subscribe
</button>
来自ajax-call 的subscribe.php
<?php
session_start();
$randomStringUser = $_POST['randomStringUser'];
// $_SESSION['id'] is set with users-id when user log in
// So if user logged in use that id as $subscriberID
if ( isset ( $_SESSION['id'] ) ) {
$subscriberID = $_SESSION['id'];
}
"SELECT id FROM userinfo WHERE randomString = ? LIMIT 1" // using $randomStringUser as ?
// Use the id found in SELECT as $subscriptionID
"INSERT INTO usersubscription ( subscriberID , subscriptionID ) VALUES ( ? , ? )" // Using $subscriberID and $subscriptionID from above as ?
答案 0 :(得分:1)
$.ajax
,因为您引用的是 slim 版本的jQuery而不是整个库。
我建议你使用完全缩小版的jQuery,这样你就可以充分利用它。
尝试使用以下内容替换<script>
标记:
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>