如何从下面的$.ajax()函数中将JavaScript变量exampleId发送到https://example.com/widget/widget-updater.php php文件中?
jQuery(document).ready(function($) {
var element = document.getElementById('widget');
var exampleId = element.getAttribute('attributeExample');
alert(exampleId); /* This prints out correctly into a pop up box */
$.ajax({
type: "GET",
url: "https://example.com/widget/widget-updater.php"
});
})();
我知道如何通过$_ get‘’exampleId‘在PHP中获取变量,但是我不知道如何通过上面的$.ajax()函数将它发送到PHP文件中。谢谢。
以下是代码:
<script
src="https://example.com/widget/externalJSfileContainingTheCodeBelow.js"
async></script><div id="widget" dataVar="1"></div>
这里是Javascript / jQuery代码
(function () {
var jQuery;
if (window.jQuery === undefined) {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
(document.getElementsByTagName("head")[0] ||
document.documentElement).appendChild(script_tag);
} else {
jQuery = window.jQuery;
main();
}
function scriptLoadHandler() {
jQuery = window.jQuery.noConflict(true);
main();
}
function main() {
jQuery(document).ready(function ($) {
var element = document.getElementById('widget');
var numberVariable = element.getAttribute('dataVar');
alert(numberVariable);
$.ajax({
type: "GET",
url: "https://example.com/widget/widget-updater.php",
data: { id: numberVariable }
});
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "https://example.com/widget/widget.css"
});
css_link.appendTo('head');
var jsonp_url = "https://example.com/cgi-bin/data.py?callback=?";
$.getJSON(jsonp_url, function (data) {
$('#widget').html(data.html);
});
});
}
})();
发布于 2018-09-12 08:11:45
只需在ajax配置中添加一个data
对象。
$.ajax({
type: "GET",
data:{'exampleId' : exampleId},
url: "https://example.com/widget/widget-updater.php"
});
在内部,当查询字符串为GET时,jQuery将在url中创建查询字符串,并将成为
"https://example.com/widget/widget-updater.php?exampleId=12345"
您也可以手动创建查询字符串,但使用对象更简洁,工作量更少,也不容易出错
发布于 2018-09-12 08:11:56
如果使用的是GET响应,则可以在查询参数中传递数据。
您的ajax URL将如下所示:https://example.com/widget/widget-updater.php?exampleId=YOURDATA
$.ajax({
type: "GET",
url: "https://example.com/widget/widget-updater.php?exampleId=data"
});
在PHP中,您可以使用$_GET['exampleId']
并将为您提供data
发布于 2018-09-12 08:11:57
由于您使用的是GET
的method
,因此您可以简单地附加您的URL
IE:
$.ajax({
type: "GET",
url: "https://example.com/widget/widget-updater.php?id=12345&foo=bar"
});
或者,也可以在.ajax()
IE中使用data
属性
$.ajax({
type: "GET",
data:{id : '123456', foo: 'bar'},
url: "https://example.com/widget/widget-updater.php"
});
https://stackoverflow.com/questions/52285674
复制相似问题