繁体   English   中英

如何从jQuery的$ .ajax()函数传递php中的数据值?

[英]How to pass data value in php from jQuery’s $.ajax() function?

我正在研究如下所示的jQuery代码 ,其中我试图从jQuery的$ .ajax()函数中传递php中的数据值

HTML代码:

<td style="width:5%; text-align:center;"><button style="width:90px;" type="submit"  name="go-button" value="Go" data-id="<?php echo $key; ?>"  class=" go-btn btn btn-outline-primary">Go</button></td> 

jQuery代码:

 jQuery(document).ready(function($)
        {
            $('.go-btn').click(function()
            {
                let target = $(this).attr('data-id'),
                    spanEl = $('.file-name[data-id='+ target +']');

                $.ajax({
                    url: 'http://abc.xyz/status.php',      // http://abc.xyz/status.php is the place where all my html/php/js code is sitting. 
                    type: 'POST',
                    data: {id: target}, //change to what you want
                    success: function(res)
                    {           
                        //alert(res)
                    },
                    error: function(res)
                    {
                        alert('Hello World!')
                    }
                })
            })
        });  

PHP代码:

<?php 
     if($_SERVER['REQUEST_METHOD'] == "POST") and !empty( $_POST['go-button'] ) )
    {       
     $value = $_POST['id'];
     print_r($value);        // Line #A   // it doesn't print any value. 
     foreach ($mp4_files as $f)  // Line#B
     { 
            // conversion of mp4 into mp3 is happening.
     }
    }
?>          

问题陈述:

我已通过$value=$_POST['id']; 在上面的PHP代码中,但在调试print_r($value); 它不会打印任何值。

我想知道我应该在php中做出哪些更改,以便我能够从php中的AJAX函数传递数据值。

问题不在于ajax而在于jquery。 你试图从类.go-btn获取data-id,但是如果你有多个具有相同类的按钮,JS将不会检测你按下了哪个按钮。

解决方案是在表上设置类,让jquery检测表中的所有按钮,如下所示:

<table class="go-table">
<td style="width:5%; text-align:center;">
    <button style="width:90px;" type="submit"  name="go-button" value="Go" data-id="<?php echo $key; ?>"  class=" go-btn btn btn-outline-primary">Go</button>
</td>   <td style="width:5%; text-align:center;">
    <button style="width:90px;" type="submit"  name="go-button" value="Go" data-id="<?php echo $key; ?>"  class=" go-btn btn btn-outline-primary">Go</button>
</td>   

并且为了你的jquery改变它:

$('.go-table').on('click', '.go-btn', function()
        {
            let target = $(this).attr('data-id'),
                spanEl = $('.file-name[data-id='+ target +']');

它应该获取data-id属性。 另外,如果您使用的是ajax,则不需要在按钮上输入提交。

暂无
暂无

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

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