从ajax调用php

时间:2016-11-07 11:58:33

标签: php jquery ajax

我尝试非常基本的东西而且它不起作用: (我正在接受警报'测试'以及那个:()

<script name="text/javascript">
    function myFunction(part_id, product_id, type)
    {
        alert('test');
        $.ajax({
            type: 'post',
            url: '2.php',
            data: {lname: "www", name: "Natalie"},
            complete: function (txt) {
                alert("complete");
                alert(txt);
            }
        });
    }
</script>

on 2.php我只有一行(在同一目录下):

    echo "test has been run";

2 个答案:

答案 0 :(得分:0)

success事件一起使用。它将获得php结果。

See the different between success() & complete()

<script name="text/javascript">
    function myFunction(part_id, product_id, type)
    {
        alert('test');
        $.ajax({
            type: 'post',
            url: '2.php',
            data: {lname: "www", name: "Natalie"},
           complete: function (txt) {
               //do something
            },
            success: function (result) {
                alert("success");
                alert(result);//test has been run
            }
        });
    }
</script>

答案 1 :(得分:0)

Ajax将返回对象数据:

Object {readyState: 4, responseText: "test has been run", status: 200, statusText: "OK"}

您必须从该对象获取响应文本。

function myFunction(part_id, product_id, type)
{
    alert('test');
    $.ajax({
        type: 'post',
        url: '2.php',
        dataType:'text',
        data: {lname: "www", name: "Natalie"},
        complete: function (txt) {
        console.log(txt);
            alert("complete");
            alert(txt.responseText);
        }
    });
}