[英]Jquery Ajax. Sending post with values from inputs with tampermonkey
[英]jQuery and AJAX. POST only gives NULL
我正在Cloud9中执行此操作。
我的计划是制作一个图片库。
在第一页上:
在首页上,我做了几个分类。 单击其中一张图片时,以下代码应激活。 代码触发,jQuery移至下一页。
问题是,AJAX发送ID,但它从未到达其他页面。 发送的ID为字符串,其中包含正确的单词。
但是,捕获POST的其他页面将无法接收它:变量的类型保持为NULL,并且不包含任何内容。
第一页代码(mainpage.php):
$(document).ready(function(){
getContent("mainpage.php");
});
function getContent($sivu){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("kuvaa").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", $sivu, true);
xhttp.send();
}
$(document).on("click", ".picture", function(){
var pictureId = $(this).attr("name");
//window.alert(jQuery.type(pictureId)); //type is string
//window.alert(pictureId); // content is what it should be
var request = $.ajax({
url: 'folders.php',
type: 'POST',
data: {
'idd': pictureId
},
success : function() {
getContent("folders.php")
},
error : function(err) {
// in case of error
console.log(err);
alert('error');
},
dataType: "html"
});
});
第二页上的变量(folders.php),什么都不会得到:
$picId = $_POST["idd"];
第一页仍然正确读取folder.php文件(这意味着它成功发送了POST,因为成功运行getContent是必需的)。
任何想法都欢迎。
编辑,工作解决方案:
单击图片时:
$(document).on("click", ".picture", function(){
var pictureId = $(this).attr("name");
getNewContent(pictureId);
});
这就是:
function getNewContent($idd){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("kuvaa").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "/folders.php?idd="+$idd, true);
xhttp.send();
}
我建议您将参数从页面传递到其他查询字符串,如果您的页面不需要后端信息,则可以使用Javascript捕获值,如果不需要,则可以基于Hachachin的答案获取值。
/phpscript.php?idd=151
使用此脚本,您可以从查询字符串获取idd
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)", "i"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var id = getParameterByName('idd');
您使用了错误的dataType。
var settings = {
type: "POST",
dataType : "json"
beforeSend: function () {
self.enable(false);
}
};
$.ajax(settings).done(function (data, textStatus, jqXHR){})
如果您需要将大对象传递给服务层以进行读取操作,则由于GET具有大小限制,因此可能必须使用POST。
我猜你的页面php不能那样工作,直到将它放在服务器中。 folder.php,应将其移至wampserver。 我想这就像C:\\ Wamp \\ www \\ Folder \\ folder.php这样,您的网址就是
url:'localhost/Folder/folder.php'
并且您需要捕获成功接收到的数据。
success : function(data) {
getContent(data);
},
我想你还会有其他错误
使用xhttp.open("GET",/phpscript.php?id=151, true);
发送ID xhttp.open("GET",/phpscript.php?id=151, true);
,并在php脚本中使用$ _GET。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.