gpt4 book ai didi

javascript - 使用 AJAX 将 javascript 变量传递给 PHP

转载 作者:可可西里 更新时间:2023-10-31 23:46:21 27 4
gpt4 key购买 nike

我有 1 个 javascript 变量,我想将 i 传递给我的 php 文件。我搜索了一下,发现可以使用 ajax 但我真的不知道如何使用它!这是我的代码。我哪里做错了?我的 .js 文件:

var message1 = message.message;

var jq = document.createElement('script');
jq.src = "https://code.jquery.com/jquery-1.10.2.js";
document.querySelector('head').appendChild(jq);

$(document).ready(function() {
$.ajax({
type: "POST",
url: 'http://localhost/a.php',
data: { newMessages : message1 },
success: function(data)
{
alert("success!");
}
});
});

我的 a.php 文件:

<?php
if(isset($_POST['newMessages']))
{
$uid = $_POST['newMessages'];
echo $uid;
}
?>

最佳答案

Listen onload event of the asynchronously loaded script and execute your function in callback function.[Ref]

试试这个:

function loadScript(src, callback) {
var s,
r,
t;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.onload = s.onreadystatechange = function() {
if (!r && (!this.readyState || this.readyState == 'complete')) {
r = true;
callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
}

var message1 = "My message";
loadScript('https://code.jquery.com/jquery-1.10.2.js', function() {

$(document).ready(function() {
$.ajax({
type: "POST",
url: 'http://localhost/a.php',
data: {
newMessages: message1
},
success: function(data) {
alert("success!");
}
});
});
})

关于javascript - 使用 AJAX 将 javascript 变量传递给 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34822613/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com