0

我有以下表格:

<p>Choose your page:</p>
<form id="ChartsForm" onsubmit="return submitForm();">
    <select name="accmenu" id="accmenu" style="width:300px;">
        <?php
        $user_accounts = $facebook->api('/me/accounts','GET');
        foreach($user_accounts['data'] as $account) {
        ?>
            <option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
        <?php
        }
        ?>
    </select>
    <p>Choose your insights:</p>
    <div class="chartsbuttons">
        <input type="submit" name="submit" value="Daily new likes">
        <input type="submit" name="submit" value="Daily unlikes">
        <input type="submit" name="submit" value="Daily page views">
    </div>
</form>

其中包含一个选择和三个测试提交按钮,称为:“每日新喜欢”、“每日不喜欢”和“每日页面浏览量”。我使用了在 submitForm 函数中定义的 ajax 调用:

function submitForm() {
    $.ajax({type:'GET', url: 'check.php', data:$('#ChartsForm').serialize(), success:
        function(response) {
            alert(response);
        }});
    return false;
};

现在检查所选选项值是否发送到 php 脚本并提醒我必须是 facebook 页面 ID 的响应。这是php脚本:

<?php
echo $_GET['accmenu'];
?>

这工作正常,但我将为每个提交按钮创建一个 php 文件以发送请求。示例:如果我按下“每日新点赞”,它将向 newlikes.php 发送一个获取请求,如果我按下“每日页面浏览量”,它将向 pageviews.php 发送一个获取请求。我只定义了一种形式,我想保持这种形式。如何根据提交按钮使用 JQuery Ajax 发送到特定的 url?我必须为每个输入创建一个新的 JavaScript 函数吗?表格怎么样,我必须创建新的?如果我创建新的选择将不会对他们每个人都可用,对吗?我真的需要指导,因为我被困在这个问题上。任何帮助表示赞赏。

4

1 回答 1

0

With PHP, you should not need to set up 3 separate files to perform the requests unless you really want to. You should be able to use your existing function with a few modifications to perform the heavy lifting, but here is a modification that calls a different file based on parameter specified:

function submitForm(action) {
    $.ajax({type:'GET', url: action + '.php', data:$('#ChartsForm').serialize(), success:
        function(response) {
            alert(response);
        }});
    return false;
};

Next you would assign some attribute to the buttons, and bind the click event to trigger your function:

HTML

<input type="submit" name="submit" value="Daily new likes" data-action="new_likes">

JavaScript

$("input[type='submit']", "#ChartsForm").on("click", function(e){
  e.preventDefault();
  submitForm($(this).attr("data-action"));
});
于 2013-04-29T14:54:30.767 回答