簡體   English   中英

JQuery / AJAX無法從PHP文件獲取響應

[英]JQuery/AJAX Unable to Get Response from PHP file

我正在嘗試為我的wordpress網站運行服務器端python腳本。 我可以在php函數中調用python文件,並以簡碼形式在網站上運行它。 因此,php文件正在工作。 我遇到的問題是構建我的JQuery並從php文件獲取響應。 我正在嘗試進行hello_world設置以調試問題

AJAX查詢:

<script >

function myFunction() {
  alert("Testing button");
}

function HelloWorldShortcode() {
    jQuery(document).ready( function($) {

        $.ajax({
            dataType: 'json', 
            method: 'POST',
            url: "http://localhost/wp-content/helloworld.php",
            data: {
                action: 'helloworld'
            },
        error: function (data) {
            alert("bad");
        },
        success: function (response) {
            alert(response);
        }
        });

    })
}

和PHP文件:

<?php # -*- coding: utf-8 -*-

ini_set('display_errors', 1);

function hello_world() {

    $test = 'hello';
    return $test;

}

if (isset($_POST['helloworld'])) {
    return hello_world();
}

我也嘗試過使用GET而不是POST。 當我在瀏覽器中訪問php文件時,我沒有收到任何錯誤,而到達ajax查詢的success部分,因為我沒有收到任何錯誤消息。 如何訪問php文件中的hello_world函數並顯示輸出?

謝謝

您正在使用參數的值,而不是參數本身...

if (isset($_POST['action'])) {
    echo hello_world();
    // Or json_encode(hello_world()); for returning an Array 
}

要么

if ($_POST['action'] == 'helloworld') {
    return hello_world();
    // Or json_encode(hello_world()); for returning an Array 
}

您將執行以下操作:

if (isset($_POST['helloworld'])) {
    echo hello_world();
    // Or json_encode(hello_world()); for returning an Array 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM