简体   繁体   English

无法通过ajax将javascript变量传递给PHP?

[英]Unable to pass javascript variable to PHP through ajax?

I have searched through a couple of QA here at stackoverflow, none of solutions seemed to help. 我在stackoverflow上搜索了两次质量检查,似乎没有一种解决方案可以帮助您。 I am trying to pass input to my PHP file but for some reason the input doesn't get passed from javascript to and it keeps on returning undefined on the console. 我正在尝试将input传递给我的PHP文件,但是由于某种原因, input没有从javascript传递给它,并且一直在控制台上返回undefined

my javascript: 我的JavaScript:

$.ajax({
    type:"GET",
    url:"go.php",
    data:{input:input},
    success:function(data){
        console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
    }
});

my php: 我的PHP:

<?php
$input = $_GET['input']; //$input here is empty

$keywords= explode(" ",$input);
$link = "https://mp3skull.wtf/search_db.php?q=" . $keywords[0];

for($i = 1; $i < count($keywords); $i++){
    $link .= "+" . $keywords[$i];
}
$link .= "&fckh=1d41a1579f21a921d1008d90dc6246a7";
echo $link; //$keywords is not appended to $link
?>

该代码可能可以从ajax调用之外的console.log正常工作。

hi first you need to declare it as a variable. 嗨,首先,您需要将其声明为变量。 Second does your variable really have a value? 其次,您的变量真的有价值吗? I'll give u sample you can run your code do it something like this 我给你样本,你可以运行你的代码做这样的事情

var input = $("#input").val();

$.ajax({
type:"GET",
url:"go.php",
data:{input:input},
success:function(data){
    console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
}
 });

hope this helps 希望这可以帮助

If you have the following Html: 如果您具有以下HTML:

<input type="text" class="field" />
<input type="button" class="button">

You should use the following script: 您应该使用以下脚本:

$(document).ready(function() {
    $('.button').click(function(){
        $.ajax({
            type:"GET",
            url:"go.php",
            data:{'input':$('input.field').val()},
            success:function(data){
                console.log(data);
            }
        });
    });
});

I think it's because when you send data in "data: { input: input } " are defining the variable input with the same name. 我认为这是因为当您在“ data:{input:input}”中发送数据时,正在定义具有相同名称的变量input。 It should be like that 应该是这样

 var inputValue = $("#idInput").val();
 $.ajax({
    type:"GET",
    url:"go.php",
    data:{input:inputValue},
    success:function(data){
        console.log(data);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM