通过ajax将值传递给另一个脚本

时间:2015-12-21 12:15:11

标签: javascript php jquery ajax

下面是一段放在for循环中的代码

for( some condition will go here )
  {
        echo "<td>
        <a href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
       </td>";
  }

点击它后,用户会被定向到event.php页面,同时,event_id和action参数也会被转发,

但不是这个 我希望通过ajax将event.php页面调用到第一页,我尝试了这个

<script>
function chk()
    {
        $.ajax({
            type:"post",
            url: "event.php",
            data:dataString,
            cache:false,
            success: function(html)
                {
                    $('#msg').html(html);
                }
            })  ;
        return false;
    }               
</script>

echo 
"<td>
    <a onclick='return chk()'>". ($i - $startday + 1) . "</a>
</td>";

但它不起作用,我也希望你在每次点击时通过ajax将event_id和动作参数传递到event.php页面,任何人都可以告诉你如何做到这一点

5 个答案:

答案 0 :(得分:0)

应该是这样的

$.ajax({
    type : "post",
    url : "event.php",
    data : {
        "event_id":"-id of the event-",
        "action":"-0action paramter-"
    },
    cache : false,
    success : function(html)
    {
        $('#msg').html(html);
    }
});

答案 1 :(得分:0)

建立你的循环添加一个类:

echo "<td>
        <a class='anEvent' href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
     </td>";

然后使用:

<script type="text/javascript">
$('.anEvent').on('click',function(e){
    e.preventDefault();
    $('#msg').load($(this).attr('href'));
})
</script>

答案 2 :(得分:0)

您可以使用data属性和$.post请求,如果您可以避开inline-events并在我的示例中为您的链接指定一个标识符(类ajax-link),则会更好,因为您的代码将从循环中创建,因此我们不必使用id,因为id在同一文档中应该是唯一的)然后您可以使用它将click事件附加到a标记,请查看以下示例:

PHP:

"<td>
     <a class='ajax-link' data-event-id=".$datee2." data-action='Details'>". ($i - $startday + 1) . "</a>
</td>";

JS:

$('body').on('click', '.ajax-link', function(e){
    e.preventDefault();

    var url = $(this).data('action');
    var event_id = $(this).data('event-id');

    $.post(url, {event_id: event_id, action: action}, 
        function(html)
        {
            $('#msg').html(html);
        }
    });
})

希望这有帮助。

答案 3 :(得分:0)

这是你可以做的事情

<a href="#" class="myclass" data-id="'.$someID.'" data-action="'.$someAction.'">

和js将是

$(".myclass").on("click", function(){
    var id = $(this).data("id");
    var action = $(this).data("action");

$.ajax({
    type : "post",
    url : "event.php",
    data : {
        "id":id,
        "action":action
    },
    cache : false,
    success : function(html)
    {
        $('#msg').html(html);
    }
});
});

答案 4 :(得分:0)

问题是您正在点击开始加载event.php的链接。 您应该使用event.preventDefault()来避免chk()函数中的默认操作。

function chk()
    {
        event.preventDefault();
        $.ajax({
            type:"post",
            url: "event.php",
            data:dataString,
            cache:false,
            success: function(html)
                {
                    $('#msg').html(html);
                }
            });
            return false;
        }  
相关问题