将$ .ajax分配给变量 [英] Assign $.ajax to variable

查看:107
本文介绍了将$ .ajax分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有得到任何输出id_function.php工作得很好可以有人请帮帮我吗?

I'm not getting any output the id_function.php works perfectly fine can anyone please help me?

JavaScript

JavaScript

 function get_details()
    {
        var oriz = document.getElementById("from").value;
        var dizz = document.getElementById("to").value;

        var id_orig_diz = $.ajax({
            type: "POST", 
            url: 'id_function.php?orig='+oriz+'&des_id='+dizz,
            dataType: "text", 
            async: false
                        }).responseText;
        alert(id_orig_diz); 

    }

这是我的PHP,但我没有得到任何id

This is my PHP but I'm not getting any id

            <?php
            $name_1 = $_GET['orig'];
            $name_2 = $_GET['des_id'];
            try {
                $dbuser = "kim";
                $dbpass = "kim";
                $conn = new PDO('mysql:host=localhost;dbname=destination', $dbuser, $dbpass);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    
                $stmt = $conn->prepare("SELECT pl_id FROM view_places WHERE name = :name LIMIT 1");

                $stmt->bindParam(':name',$name_1); 
                $stmt->execute();
                $result_1 = $stmt -> fetch();
                $res1 = $result_1["pl_id"];  

                $stmt->bindParam(':name', $name_2); 
                $stmt->execute(); 
                $result_2 = $stmt -> fetch(); 
                    $res2 = $result_2["pl_id"];  
                    echo   'origin_number:'.$res1. ', '.'destination_id:'.$res2;
                }   catch(PDOException $e) {
                        echo 'ERROR: ' . $e->getMessage();
                }

            ?>


推荐答案

这不起作用,因为AJAX调用是异步的,这意味着它们在执行后不会立即返回值。它必须转到服务器,让服务器端代码运行,然后提供一个值。可以认为它在许多方面类似于用另一种语言开始一个线程;你必须等待线程将控制权交还给你的应用程序。

This will not work because AJAX calls are asynchronous which means that they don't immediately return a value after you execute them. It has to go out to the server, let the serverside code run and then provide a value back. Think of it as similar in many ways to kicking off a thread in another language; you have to wait for the thread to yield control back to your application.

var id_orig_diz = $.ajax({
    type: "POST", 
    url: 'id_function.php?orig='+oriz+'&des_id='+dizz,
    dataType: "text", 
    async: false
}).responseText;

您需要做的是设置这样的结果处理程序:

What you need to do is set a result handler like this:

var id_orig_diz;
$.ajax({
    type: "POST", 
    url: 'id_function.php?orig='+oriz+'&des_id='+dizz,
    dataType: "text", 
    async: false,
    success: function(data){
        id_orig_diz = data; //or something similar
    }
});

这篇关于将$ .ajax分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆