gpt4 book ai didi

php - 在 JQuery 中传递多个数据

转载 作者:行者123 更新时间:2023-12-01 02:53:35 25 4
gpt4 key购买 nike

我是 Ajax 新手,我正在尝试将多个变量传递到我的 PHP 文件,但它并没有真正起作用。基本上问题是,当我传递多个变量时,它会停止工作。下面我详细解释一下。

这是我的 ajax 代码片段。我用它来上传文件:

var mdata = new FormData();
mdata.append('image_data', $(this)[0].files[0]);
var id = $id //$id is passed inside my function. Just assigning it but not necessary

jQuery.ajax({
type: "POST", // HTTP POST
processData: false,
contentType: false,
url: "includes/ul.php", //Ajax Calls here
data: mdata, //Form variables
dataType: 'json',

上面的代码片段有效。如您所见,我只传递 mdata

现在,当我尝试传递多个数据时会出现问题。上传停止工作。我尝试发送 $_POST 的电子邮件,但收到一个空数组。下面是我尝试过但不起作用的代码:

data: {mdata: mdata, "prodID":id} //See how I pass multiple variables now

这是我的 PHP 代码。基本上,当我仅传递 mdata 时,一切正常,如第一个代码片段所示。但是,对于多个变量,它不起作用(即我的 $_POST)无法获取值,甚至上传也不起作用:

<?php
$fullSize = "../prod/full_size/";
$thumb = "../prod/thumb/";
$_thumb = "prod/thumb/";
$image_height = 520;
$image_width = 650;
$id = $_POST["prodID"];

//gets image size info from a valid image file
$image_size_info = getimagesize($_FILES['image_data']['tmp_name']);


//initiate ImageMagick
$image = new Imagick($_FILES['image_data']['tmp_name']);

//Upload Full size
$image->writeImages($fullSize. $_FILES['image_data']['name'], true);

//Resize for thumb
if($image_type=="image/gif") //determine image format
{
//if it's GIF file, resize each frame
$image = $image->coalesceImages();
foreach ($image as $frame) {
$frame->resizeImage( $image_height , $image_width , Imagick::FILTER_LANCZOS, 1, FALSE);
}
$image = $image->deconstructImages();
}else{
//otherwise just resize
$image->resizeImage( $image_height , $image_width , Imagick::FILTER_LANCZOS, 1, FALSE);
}

//write image to a file
$results = $image->writeImages($thumb. $_FILES['image_data']['name'], true);

//output success response
if($results){
$response = json_encode(array('type'=>'success', 'msg'=>'Success'));
die($response);
}


?>

感谢任何帮助。谢谢:)

最佳答案

问题是因为您需要将 FormData 直接传递给 $.ajax 调用,而不是包装在对象中。您可以使用 FormDataappend() 方法向其中添加其他字段:

var mdata = new FormData();
mdata.append('image_data', $(this)[0].files[0]);
mdata.append('prodID', id); // < data appended here

jQuery.ajax({
type: "POST", // HTTP POST
processData: false,
contentType: false,
url: "includes/ul.php", //Ajax Calls here
data: mdata, //Form variables
dataType: 'json'
});

关于php - 在 JQuery 中传递多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33505562/

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