weixin_33749242 2017-10-26 18:17 采纳率: 0%
浏览 17

Ajax返回值

I am trying to figure out how to send back a value to the Ajax popup box. Currently, the value that gets returned is just the JSON that comes back from the API call. I would much rather use jsondecode to pull out a specific value and have that return, or... lets not even get that complex. I just want to set a variable equal to some message such as "API GET complete" and return that to the Ajax box. This will also help with troubleshooting so I can return a variable to see if things are working. As I said, currently the Ajax popup just displays the JSON that comes back from the API call. This is my first time working with both Ajax and curl_setopt so if you can please make recommendations with examples, that would be fantastic! Thank you!

test.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('.button').click(function(){
        var clickBtnValue = $(this).val();
        var ajaxurl = 'auto.php',
        data =  {'action': clickBtnValue};
        $.post(ajaxurl, data, function (response) {
            alert(response);
        });
    });

});
</script>
</head>
<body>
    <input type="submit" class="button" name="test" value="Test" />
</body>
</html>

auto.php

<?php
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'Test':
            Test();
            break;
        case 'to_the_n':
            to_the_n();
            break;
    }
}
function Test() {
    $ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
    $result = curl_exec($ch);
    $message = "Yay it worked" //Send this message back to Ajax popup, not the API reply
    exit;
}
?>

* UPDATE *

enter image description here enter image description here

* UPDATE *

enter image description here

  • 写回答

1条回答 默认 最新

  • 狐狸.fox 2017-10-26 18:20
    关注

    You can just echo the value from php and it will be alerted in the Ajax success function.

    echo 'Yay it worked!! ';
    
    <?php
    if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'Test':
           if(Test() == true) {
           echo('yay it worked!! '); 
           exit; 
           }
            break;
        case 'to_the_n':
            to_the_n();
            break;
    }
    }
    function Test() {
    $ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
    $result = curl_exec($ch);
    return true; 
    }
    ?>
    
    评论

报告相同问题?