I have 1 javascript
variable and i want to pass i to my php
file. i search about it and i find that to use ajax
but i don't really know how use it ! here is my code . where am i do wrong ? my .js file :
我有1个javascript变量,我想把我传递给我的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!");
}
});
});
my a.php
file :
我的a.php文件:
<?php
if(isset($_POST['newMessages']))
{
$uid = $_POST['newMessages'];
echo $uid;
}
?>
2 个解决方案
#1
1
Listen
onload
event of theasynchronously
loaded script and execute your function incallback
function.[Ref]监听异步加载脚本的onload事件,并在回调函数中执行函数。[Ref]
Try this:
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!");
}
});
});
})
#2
-1
The php file should return data in json format. You can add complete, always, error to your Ajax to better catch the result
php文件应以json格式返回数据。您可以向Ajax添加完整的始终错误,以便更好地捕获结果
#1
1
Listen
onload
event of theasynchronously
loaded script and execute your function incallback
function.[Ref]监听异步加载脚本的onload事件,并在回调函数中执行函数。[Ref]
Try this:
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!");
}
});
});
})
#2
-1
The php file should return data in json format. You can add complete, always, error to your Ajax to better catch the result
php文件应以json格式返回数据。您可以向Ajax添加完整的始终错误,以便更好地捕获结果