简体   繁体   English

PHP脚本不接收jQuery POST

[英]PHP Script Does not Receive jQuery POST

First off, I'm a bit of a jQuery noob and a total PHP noob so I'm sorry if this is a stupid question (although I have searched the Internet and, specifically, this site up and down could not figure out what I'm doing wrong). 首先,我是一个jQuery noob和一个总的PHP菜鸟所以我很抱歉,如果这是一个愚蠢的问题(虽然我已经搜索了互联网,特别是,这个网站上下不知道我是什么我我做错了。 Also, if you see any other mistakes/messy code, etc., don't hesitate to tell me :). 此外,如果你看到任何其他错误/凌乱的代码等,请不要犹豫告诉我:)。

I'm trying to create a gallery where I have a previous and a next button. 我正在尝试创建一个库,我有一个前一个按钮和一个下一个按钮。 When you click previous, the src-attribute of the img-tag gets changed to the previous image via jquery and the same with the next buton and the next image. 当您单击上一个时,img-tag的src-attribute将通过jquery更改为上一个图像,并与下一个buton和下一个图像相同。 However, I want it to return to the last image when you press on the previous button and the current image is the first image. 但是,当您按下上一个按钮并且当前图像是第一个图像时,我希望它返回到最后一个图像。 I need this to happen dynamically as I have several of these galleries with a different total number of pictures in them. 我需要这个动态发生,因为我有几个这些画廊中的图片总数不同。 Now, my current approach is (roughly): 现在,我目前的方法是(大致):

  • Send a direction parameter from the clicked button to my image-toggle function (either "backward" or "forward") 从单击的按钮发送方向参数到我的图像切换功能(“向后”或“向前”)

  • Extract the image source's file path and post it to an external PHP script which then counts the number of files in that directory. 提取图像源的文件路径并将其发布到外部PHP脚本,然后计算该目录中的文件数。

  • Check whether the direction parameter is forward. 检查方向参数是否向前。 If yes, increment the number at the end of the current image's file name by one. 如果是,请将当前图像文件名末尾的数字增加1。 If not, substract one (resulting in a non-existent file name). 如果不是,则减去1(导致文件名不存在)。 This new file name is assigned to the nextImage variable. 此新文件名将分配给nextImage变量。

  • Check whether nextImage exists. 检查nextImage是否存在。 If yes, assign it as the of the img src-attribute. 如果是,请将其指定为img src-attribute的。 If not, get the file count from the external PHP script, implement it into nextImage as the file number and then assign that to the src-attribute. 如果没有,从外部PHP脚本获取文件计数,将其作为文件号实现到nextImage,然后将其分配给src-attribute。

Most of this works. 大部分都有效。 However, getting the last image when clicking previous on the first image doesn't. 但是,在第一张图像上单击上一张图像时获取最后一张图像则不会。 I have done some debugging and narrowed it down to the point where it seems to stop working. 我做了一些调试,并将其缩小到似乎停止工作的程度。 Firebug tells me that the jQuery POST function works (and I also got the success alert) and that it posts the data I want to the PHP file. Firebug告诉我jQuery POST功能正常工作(我也得到了成功警报)并且它将我想要的数据发布到PHP文件中。 However, inside the PHP script, the if (isset($_POST["id1"])) branch is never entered. 但是,在PHP脚本中,永远不会输入if (isset($_POST["id1"]))分支。 It always goes straight to the else branch, even though I have basically copy-and-pasted the whole script from accepted answers on this site. 它总是直接进入else分支,即使我基本上从本网站上接受的答案中复制并粘贴了整个脚本。

Here's the jQuery code: 这是jQuery代码:

var nextImageLength = " ";
var nextImage = " ";
var imageString = " ";
var nextImageStr = " ";
var nextImageNmb = 0;

var countImageLength = function($countimagelength) {
    nextImageLength = nextImageStr.length;
    if (nextImageLength < 3) {
        if (nextImageLength < 2) {
            nextImage = imageString + '00' + nextImageStr + '.jpg';
        }
        else {
            nextImage = imageString + '0' + nextImageStr + '.jpg';
        }
    }
    else {
        nextImage = imageString + nextImageStr + '.jpg';
    }
}

function multiPageToggle(direction) {
    var currentImage = $(".viewport_img_high").attr("src");
    imageString = currentImage.slice( 0, 35 );
    $.ajax(
            {
            type: "POST",
                url: "countImages.php",

                data: { id1: imageString},
                success: function (count) {
                    //alert('success');

            }
    });     
    var currentImageNmb = currentImage.slice(-7, -4);
    if (direction == "forward") {
        nextImageNmb = (parseInt(currentImageNmb)) + 1;
    }
    else {
        nextImageNmb = (parseInt(currentImageNmb)) - 1;
    }
    nextImageStr = nextImageNmb.toString();
    countImageLength();
    $.get(nextImage)
            .done(function() { 
                $(".viewport_img_high").attr("src", nextImage);
         }).fail(function() { 
                 if (nextImageNmb < 1) {
                $.get('countImages.php', function(count) {
                    nextImageStr = count;
                });
                countImageLength();
                $(".viewport_img_high").attr("src", nextImage);
            }
            else {
                nextImageStr = "1";
                countImageLength();
                $(".viewport_img_high").attr("src", nextImage);
            }
         });
}   

And this is my PHP script: 这是我的PHP脚本:

<?php
if (isset($_POST["id1"])) 
{
  $imgStr = $id1;
} 
else 
{
  $imgStr = "1";
  echo "Oops. Something went really wrong here.";
}
$imagePath = "c:/xampp/htdocs/portfolio/images2/" + $imgStr + "/";
$count = iterator_count(new DirectoryIterator($imagePath));
echo $count;
?>

EDIT: I'll add some Firebug data below. 编辑:我将在下面添加一些Firebug数据。 Maybe that can help make sense of this. 也许这可以帮助理解这一点。 Response Header: 响应标题:

Connection  Keep-Alive
Content-Length  77
Content-Type    text/html
Date    Tue, 15 Jul 2014 04:26:24 GMT
Keep-Alive  timeout=5, max=100
Server  Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.9
X-Powered-By    PHP/5.5.9

Request Header: 请求标题:

Accept  */*
Accept-Encoding gzip, deflate
Accept-Language de,en-US;q=0.7,en;q=0.3
Cache-Control   no-cache
Connection  keep-alive
Content-Length  43
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    localhost
Pragma  no-cache
Referer http://localhost/portfolio/index_b.php
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0
X-Requested-With    XMLHttpRequest

Response: 响应:

array(1) {
  ["id1"]=>
  string(35) "images2/des004_large_/des004_large_"
}
0

The line: 这条线:

$imgStr = $id1;

should be: 应该:

$imgStr = $_POST['id1'];

vardump($_POST) to check all values on the array. vardump($_POST)检查数组上的所有值。 If there's only a empty array your page isn't posting anything, else it will output all the contents of your post. 如果只有一个空数组,您的页面不会发布任何内容,否则它将输出您帖子的所有内容。 Then start working around that: check all the indexes that are present and replace them in your code ;) 然后开始解决这个问题:检查所有存在的索引并在代码中替换它们;)

Okay, so I still don't know what was wrong but I simply rewrote the POST/GET parts of my jQuery script, as well as the PHP script from scratch and now it's working. 好的,所以我仍然不知道出了什么问题,但我只是重写了我的jQuery脚本的POST / GET部分,以及从头开始的PHP脚本,现在它正在工作。 Here's my new code in case anyone stumbles on this again in the future and has a similar problem. 这是我的新代码,以防将来有人再次发现这个问题,并遇到类似的问题。 I replaced the POST-$.ajax function with this (also changed some the variables in the rest of my jQuery in the meantime so don't let that confuse you): 我用这个替换了POST - $ .ajax函数(同时也改变了我jQuery其余部分中的一些变量,所以不要让你混淆):

$.post( "test3.php", {a: imageStringSlice}, function(data) {
            //alert(data);
    count = data - 2;
});

The $.get with this: 这个$ .get:

nextImageStr = count.toString();
countImageLength();
$(".viewport_img_high").attr("src", nextImage);

And the PHP script with this: 这个PHP脚本:

<?php
if( $_REQUEST["a"] )
{
    $imgstr = $_REQUEST['a'];
    settype($imgstr, "string");
    $count = iterator_count(new DirectoryIterator($imgstr));
    echo $count;
}
else {
    echo "1";
}
?>

Thanks to Barmar and especially to gcarvalho97 for helping me out :)! 感谢Barmar,特别是gcarvalho97帮助我:)!

I am super late to this one, however I struggled with the same issue recently and could not find any help anywhere. 我对这个问题已经很晚了,但是我最近在同一个问题上遇到了困难,在任何地方都找不到任何帮助。

The simple answer is that PHP does not populate the $_POST if it does not recognize a form, however the input is still available. 简单的答案是,如果PHP无法识别表单,PHP不会填充$ _POST,但输入仍然可用。

when I post (in my case json data) through javascript, I get it back from php by using this: 当我通过javascript发布(在我的情况下json数据)时,我通过使用这个从PHP获取它:

$postbody = file_get_contents("php://input");

note that it is not equivalent of a post as it is not processed, so you may need to work a lot on this. 请注意,它不等同于帖子,因为它未被处理,因此您可能需要对此进行大量工作。

more information on stream wrappers is available here: [php manual on php input][ http://php.net/manual/en/wrappers.php ] 有关流包装器的更多信息,请点击此处:[php php on php input] [ http://php.net/manual/en/wrappers.php ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM