jquery ajax 调用 - 如果 dataType 只是一个文本(字符串),则获取返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6316811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:41:15  来源:igfitidea点击:

jquery ajax call - get returning value if dataType is simply a text (string)

jquery

提问by yorgos

I have the following code.

我有以下代码。

    $.ajax({
    type: "POST",
    url:"blahblah.php",
    data: "{}",
    async: true,
    dataType: "text",
    success: function() {
       if(returning data from blahblah.php == true)
           window.location.href="http://www.blahblah.com/logout.php";
    }
}); 

1) No data need to be sent.

1) 不需要发送数据。

2) File "blahblah.php" does some processing and returns either true or false.

2) 文件“blahblah.php”进行一些处理并返回真或假。

3) I want to get the response and If true redirect to another php page.

3)我想得到响应,如果是真的重定向到另一个 php 页面。

I do not know how to read the returning data of the function in the blahblah.php file!!

blahblah.php文件中函数的返回数据不知道怎么读取!!

Thank you in advance. George

先感谢您。乔治

回答by Seth

You have to pass a variable into the successcall.

您必须将变量传递给success调用。

$.ajax({
    type: "POST",
    url:"blahblah.php",
    data: "{}",
    async: true,
    dataType: "text",
    success: function( data ) {

        console.log(data);

    }
}); 

If the success method runs then you have successfully submitted the file and can redirect with a simple document.location = "http://www.example.com/somewhere.php

如果成功方法运行,则您已成功提交文件,并且可以使用简单的重定向 document.location = "http://www.example.com/somewhere.php

回答by Kon

Have you tried setting dataType to 'json'? Also, you're not actually retrieving the response from the server on a successful callback. Try this:

您是否尝试将 dataType 设置为'json'?此外,您实际上并不是在成功回调时从服务器检索响应。尝试这个:

    $.ajax({
      type: "POST",
      url:"blahblah.php",
      data: "{}",
      async: true,
      dataType: "json",
      success: function(response) {
         if(response == true) {
             window.location.href="http://www.blahblah.com/logout.php";
         }
      }
   }); 

回答by Sangeet Shah

If your success event is not call then you may be get return data using complete event

如果您的成功事件没有被调用,那么您可能会使用 complete 事件获取返回数据

example

例子

complete: function (data) {
    alert(data.responseText);
  },

using this you can get response data in this event

使用这个你可以在这个事件中获得响应数据