我正在尝试使用 Ajax 将 jquery 变量传递给 PHP,但接收 php 文件返回错误" 未定义的索引" 代码是:
<div class="img">
<a href="ss.php">
<img id="theme_bg" src="images/themes/theme1.jpg">
</a></div>
$(document).ready(function($){
$('.img').on('click','img',function(){
var imgsrc = $(this).attr('src');
alert(imgsrc); //this is returning the img src correctly
$.ajax({
type: "POST",
url: 'ss.php',
dataType: 'json',
data: {imgpath:imgsrc },
success: function(response) {
content.html(response); // i tried alert here but it shows nothing
}
});
});});
接收 PHP 文件代码是:
<?php
$imagepath = $_POST['imgpath'];
echo $imagepath;
?>
我也用 GET 尝试过,但同样的错误。在此之前我没有使用过Ajax。我在这里检查了有关类似问题的其他回答,但没有一个与我的代码有任何重大区别。所以不知道错误是什么。.
更新了两个文件的代码屏幕截图
更新了输出的屏幕截图
你已经将数据类型设置为 json
所以PHP应该php <?php echo json_encode([$imagepath])
更好的解决方案是数据类型:文本而不是JSON。
请注意,在 $.ajax 中,数据类型用于响应而不是请求
检查 $.ajax 手动 http://api.jquery.com/jquery.ajax/
为什么你在锚中写ss.php
你不需要它,这就是为什么它在单击时重定向ss.php
并获得错误未定义的索引。
你的 html 代码应该是这样的:
<form id="myForm" method="post" action="ss.php">
<div class="img">
<img id="theme_bg" src="images/themes/theme1.jpg">
<input name="imgpath" id="imgpath" type="hidden"/>
</div>
</form>
Jquery代码:
$(document).ready(function ($) {
$('.img').on('click', 'img', function () {
var imgsrc = $(this).attr('src');
$("#imgpath").val(imgsrc); //this is returning the img src correctly
$("#myForm").submit();
});
});
SS.php
<?php
$imagepath = $_POST['imgpath'];
echo $imagepath;
?>
试试这个。将此添加到文档就绪函数
$(".img").click(function() { $.ajax({ type: "POST", url: "ss.php", data: {imgpath:imgsrc}, dataType: "text", cache:false, success: function(data){ alert(data); } });// you have missed this bracket return false; });