dqqxkq4047 2014-12-08 05:16
浏览 43
已采纳

将变量从Javascript传递到PHP并返回

The console ends up writing back

Uncaught ReferenceError: provhtml is not defined

Also, when I change up my Javascript to be the code right below, the console ends up just writing " <?= $provhtml ?>"

var provnum = "<?= $provhtml ?>";
console.log(provnum);

I'm not exactly sure what the problem is. I want $provhtml to be written inside the console when a user clicks a button named otherlistbut (I'm also not sure if there needs to be the d.preventDefault(); Here is my prov.php

<?php    
$phonenum = $_POST["phonenum"];
$provhtml = file_get_contents('http://api.data24-7.com/v/2.0?user=USERNAME&pass=PASSWORD&api=C&p1=1' . $phonenum);   
 ?>

Here are my scripts in my index.html

   $('button[name="otherlistbut"]').click(function(d) {
        lookupProvider(d);

    });
});

/************ FUNCTIONS ******************/

function lookupProvider(d) {
    d.preventDefault();
    var phonenum = $('input[name="phonenum"]').val();
    $.ajax({
        type: 'POST',
        data: {
            phonenum: phonenum
        },
        url: 'prov.php',
        success: function(data) {
            var provnum = $(provhtml);
            console.log(provnum);
        },
        error: function(xhr, err) {
            console.log("readyState: " + xhr.readyState + "
status: " + xhr.status);
            console.log("responseText: " + xhr.responseText);
        }
    });
}
  • 写回答

1条回答 默认 最新

  • dongzuan4491 2014-12-08 05:27
    关注

    In your prov.php file

    <?php    
    $phonenum = $_POST["phonenum"];
    $provhtml = file_get_contents('http://api.data24-7.com/v/2.0?user=USERNAME&pass=PASSWORD&api=C&p1=1' . $phonenum);   
    echo json_encode( array( "phonenum" => $phonenum,"provhtml"=>$provhtml)); //You should be returning the values to your ajax function
     ?>
    

    In your index.html

    function lookupProvider(d) {
        d.preventDefault();
        var phonenum = $('input[name="phonenum"]').val();
        $.ajax({
            type: 'POST',
            data: {
                phonenum: phonenum
            },
            url: 'prov.php',
            success: function(data) { //Receives the data from the php code
                var provnum = data.phonenum;
                console.log(provnum);
            },
            error: function(xhr, err) {
                console.log("readyState: " + xhr.readyState + "
    status: " + xhr.status);
                console.log("responseText: " + xhr.responseText);
            }
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?