首页 > 解决方案 > 使用 jQuery AJAX 发送 php 变量

问题描述

我正在使用图片上传 jQuery 脚本和简短的 php 脚本。它们都包含在 mainsite.php 文件中。

一切正常,期待 php 变量的传输$usr_id

如何$usr_id通过 AJAX 将 php 变量正确发送到我的服务器端脚本?

php代码

    $user = JFactory::getUser();
    $usr_id = $user->get('id');

这是我的尝试:

jQuery(function ($) {
  $(document).ready(function () {

    $("#but_upload").click(function () {

        var fd = new FormData();
        var files = $('#file')[0].files;
        var userid = <?php echo $usr_id ?>;
              
        if (files.length > 0) {
            fd.append('file', files[0]);
            fd.append('userid', userid);
            $.ajax({
                url: 'imageupload/upload.php',
                type: 'post',
                data: fd,
                contentType: false,
                processData: false,
                success: function (response) {
                    if (response != 0) {
                        $("#img").attr("src", response);
                    } else {
                        alert('file not uploaded');
                    }
                },
            });
        } else {
            alert("Please select a file.");
        }
    });
  });
})

编辑:这是表单域代码

<form method="post" action="" enctype="multipart/form-data" id="myform">
    <div >
        <input type="file" id="file" name="file" />
        <input type="button" class="button" value="Upload" id="but_upload">
    </div>
</form>

标签: phpjquery

解决方案


推荐阅读