Jquery $.post - From server to client - how does it knows what response to get?

MEM*_*MEM 0 ajax jquery .post

So we have this:

$.post('testeUpdate.php', 'someValue'
        function(dadosResposta) {
            $('#ns-nome').val(dadosResposta.nsName);
            $('#ns-endereco').val(dadosResposta.nsAddress);
        },
"json");
Run Code Online (Sandbox Code Playgroud)

From client to server: Is sends 'sameValue' to testeUpdate.php using POST.

On success, it receives the data returned by the server side script and do something with that on the client side. Correct?

There is something between the Server Side script and this Client Side script that I'm not getting.

Question: How does dadosResposta gets filled with the data returned from the serverside script ? How does it knows? How does it work? Perhaps the question may also be posed: how do jquery knows when something is "on success" ?

或者尝试另一种方式:服务器端执行脚本,在json中返回一些编码数据.直到这里好.在此之后,会发生什么?我们如何再次进入客户端部分?

[更新]再试一次:我知道:dadosResposta包含服务器端脚本返回的任何问题,它是如何知道的?他是怎么做到的?[/更新]

非常感谢,MEM

Rya*_*nal 5

jQuery .post函数使用XMLHttpRequest对象来访问传递给它的URL.服务器响应200 OK(成功)或其他响应(可能是失败).

成功时,XMLHttpRequest对象的responseText(或responseXML)属性设置为服务器返回的数据.处理响应的幕后jQuery函数然后查看您的dataType参数以确定如何处理返回的数据.在您的示例中,它尝试将其解析为对象.

假设响应是一个有效的JSON字符串,它然后将新创建的对象作为其第一个(也是唯一的)参数传递给您的回调函数,该参数已命名dadosResposta.

就是jQuery如何获取数据的方式dadosResposta.

编辑: 这里有一些代码可能与正在发生的事情类似:

$.post = function([arguments])
{
    var xhr = new XMLHttpRequest(); // not cross browser compatible, but good enough for demonstration
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === 4 && xhr.status === 200)
        {
            switch (your_dataType)  // check your data type
            {
                case 'json':
                    your_callback(json_decode(xhr.responseText));    // call your function with JSON object
                    break;
                case 'xml':
                    your_callback(xhr.responseXML);    // call your function with XML
                case ... (etc)
            }
        }
    }

    xhr.open('POST', your_URL, true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send();
}
Run Code Online (Sandbox Code Playgroud)