简体   繁体   English

IF-ELSE声明无效

[英]IF-ELSE statement not working

I'm trying my best to create a website. 我正在努力创建一个网站。 I need to create an IF-ELSE in ajax. 我需要在ajax中创建一个IF-ELSE。 It basically calls the content of an input called "greeting" and aims at writing "YES" if the user inserts a specific text and "NO" otherwise. 它基本上调用称为“问候”的输入的内容,并且如果用户插入特定文本则写入“是”,否则写入“否”。

jQuery(document).ready(function () {
    var greeting = jQuery("#greeting").val();
    jQuery("#push-me").click(function () {
        jQuery.ajax({
            type: 'POST',
            url: 'http://www.boatsandbeats.com/wordpress/wp-admin/admin-ajax.php',
            data: {
                action: 'myAjax',
                greeting: jQuery("#greeting").val(),
            },
            success: function (data, textStatus, XMLHttpRequest) {
                if (data == "XYZ") == 0 {
                    jQuery("#test-div").html('');
                    jQuery("#test-div").append("YES");
                } else {
                    jQuery("#test-div").html('');
                    jQuery("#test-div").append("NOPE");
                }
            },
            error: function (MLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});

While the rest of the code works just fine, it does not recognize the IF and takes everything as if it were true (therefore, printing "YES"). 虽然其余的代码工作正常,但它不能识别IF并将所有内容视为真实(因此,打印“是”)。

Can anybody be so kind and explain this to me? 任何人都可以这么善良并向我解释一下吗?

it is not working because your if statement is wrong 它没有用,因为你的if语句错了

 if (data == "XYZ") == 0 {

should be 应该

 if (data.greeting == "XYZ") {

}

Step 1: check if your ajax actually returns something. Step 1:检查你的ajax是否真的返回了一些东西。

...//add the following line
 success: function (data, textStatus, XMLHttpRequest) {
    console.log(data);
    alert("Data logged." + data);
...

Step 2: what do you want to test? Step 2:你想测试什么? You want to know if data (the ajax return) is a string and that string is having the value "XYZ"? 您想知道数据(ajax返回)是否为字符串且该字符串的值是否为“XYZ”?

 //change 
 if (data == "XYZ") == 0  
 //to
 if (data === "XYZ") 

Note the triple === it's not the same as == . 注意三元组===它与==不一样。 The difference is that === will check if the variables have the same value and the same type. 区别在于===将检查变量是否具有相同的值和相同的类型。

In addition, in Javascrip can compare string similar to your style like using localeCompare() : 此外,在Javascrip中可以比较类似于您的样式的字符串,就像使用localeCompare()

if (data.localeCompare("XYZ") === 0) if(data.localeCompare(“XYZ”)=== 0)

 /* strA.localeCompare(strB); Returns:   
 0:  exact match    
-1:  strA < strB    
 1:  strB > strA    
 */

UPDATE: 更新:

Assuming your php function is as the following: 假设你的php功能如下:

function myAjax()
{
    $greeting = $_POST['greeting'];
    if (isset($_POST['greeting']))
        $greeting = $_POST['greeting']; 
    $results = "<h2>".$greeting."</h2>";
    die($results);
}

This is what's going to happen. 这就是将要发生的事情。

{
    //$greeting is being assigned a value from POST greetings, // in post is empty then $greeting will be empty as well. 
    $greeting = $_POST['greeting'];
    //You are validating POST greeting, although you already captured it's value and put it in $greeting, so why not using $greeting here instead?
    if (isset($_POST['greeting']))// this if has no {} so ONLY the first line after will be included in this IF condition. 
        $greeting = $_POST['greeting'];
    // this line will be exectue no matter what, so the value of $greeting will be entered into a string enclosed with <h2> tags. if POST greeting is empty, then $greeting will be empty of course. 
    $results  = "<h2>" . $greeting . "</h2>";
    //the variable $result now has "<h2></h2>" as it's value if $greeting is empty. 
    die($results); //echoing $result, or 
}

So, since you have confirmed that you are receiving " 所以,既然你已经确认你收到了“

" as a value for data variable returned from AJAX. Why are you comparing it to XYZ in your condition? “作为从AJAX返回的数据变量的值。 为什么在你的条件下将它与XYZ进行比较?

In your JS you are assigning "#greeting").val() to a variable greeting, then you use that variable as an array attribute for your ajax{data{greeting:jQuery("#greeting").val() }} 在你的JS中,你将"#greeting").val()分配给变量问候语,然后你将该变量用作ajax{data{greeting:jQuery("#greeting").val() }}的数组属性ajax{data{greeting:jQuery("#greeting").val() }}

  var greeting = jQuery("#greeting").val();// what is the use of this line? 

Enclose your object attribute with "" eg "greeting". 用“”例如“问候”包围您的对象属性。

  data: { "action": 'myAjax', "greeting": jQuery("#greeting").val(),// what is the value of "#greeting").val()? }, 

IF condition system is looks wrong, IF条件系统看起来不对,

if (data == "XYZ") == 0

You should use only, no need == 0 你应该只使用,不需要== 0

if (data == "XYZ"){
    //.... code here 
}

OR If ajax response in json 或者如果json ajax响应

if (data.key == "XYZ"){
    //.... code here 
}

首先你需要检查数据是否会打印XYZ或打印[Object object]如果[Object object]那么你需要检查data.d ==“XYZ”

in success function first parse then compare like this 在成功函数中首先解析然后比较这样

 var response=$.parseJSON(data);

 if(response.field=="XYZ")
 {
    jQuery("#test-div").html('');
    jQuery("#test-div").append("YES");
 }
 else
{
     jQuery("#test-div").html('');
    jQuery("#test-div").append("NOPE");
}

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

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