javascript - 使用Ajax运行php函数

标签 javascript php jquery ajax

您好,我正在尝试创建一个按钮,该按钮将调用 php 函数以从 Web 应用程序将产品添加到 Shopify

首先这是我的 result.php 文件,它成功显示了亚马逊产品 http://codepad.org/MPs4y1Qu

在那里你会发现两件重要的事情

第一<button type="button">add</button>

<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            $.ajax({
                type: 'POST',
                url: 'create_product.php',
                success: function(data) {
                    prompt(data);
                }
            });
        });
    });
</script>

问题是,当我单击“添加”按钮时,它显示页面的 HTML,但 create_product.php 上没有任何反应。文件。我希望它调用该函数。另一方面,我的代码 create_product很好,可以 100% 单独工作,但不能与我的网络应用程序一起工作。

这是我的create_product.php代码:

http://codepad.org/at7LtcMK

最佳答案

您的 AJAX 调用将通过 POST 或 GET 发送数据,然后您可以使用它执行任何操作,也可以将某些内容返回到您的脚本。就这么简单。

http://api.jquery.com/jquery.ajax/

让我们来看一些例子。如果您想在服务器上创建 A+B,您将需要一个包含如下输入的表单:

<form id="yourform">
    <div><input name="A" type="text" /></div>
    <div><input name="B" type="text" /></div>
</form>

然后您将编写一些脚本来说明您的表单在提交时将执行的操作。当您使用 jQuery 时,让我们使用 jQuery:

$("#yourform").submit(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST", //or "GET", if you want that
        url: "yourfile.php",
        data: $(this).serializeArray(), //here goes the data you want to send to your server. In this case, you're sending your A and B inputs.
        dataType: "json", //here goes the return's expected format. You should read more about that on the jQuery documentation
        success: function(response) { //function called if your request succeeds
            //do whatever you want with your response json;
            //as you're learning, try that to see on console:
            console.log(response);
        },
        error: function(response) { //function called if your request failed
            //do whatever you want with your error :/
        }
    });
});

但是你在服务器上做什么? 好吧,我只是想返回我的输入,只是为了检查一下。这是我的 PHP:

<?php
    header("Content-type: application/json; charset=utf-8"); //that's required to return any JSON data
    if(isset($_POST, $_POST['A'], $_POST['B']))
        exit(json_encode($_POST));
    else
        exit("INVALID REQUEST.");
?>

这就是您可以使用 AJAX 发送信息以在 PHP 上执行某些操作的方式。

关于javascript - 使用Ajax运行php函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863942/

相关文章:

javascript - 使用 JavaScript 进行 ASP.NET 回发(单击 LinkBut​​ton)-发生回发但不发生 Click 事件

javascript - 将 arraybuffer 的一部分绘制到 Canvas 上的最佳方法是什么?

javascript - 如何通过单击屏幕上的表格列来弹出图像

javascript - 我怎样才能阻止玩家离开网格?

javascript - 创建表格标题的双向固定滚动

javascript - 在 uploadify 中动态设置属性

javascript - 使用 Link 标签并在 React 中传递数据

java - 从java到php5?

php - 如何在不删除mysql中当前值的情况下更新行?

php - Visual Studio Code : Spawn UNKNOWN