简体   繁体   English

用jquery $ .ajax返回json调用PHP函数

[英]Call PHP function with jquery $.ajax return json

How can I call (if even possible) a PHP function from javascript targeting one method just like ASP.NET. 如何从javascript中调用(如果可能的话)来自javascript的PHP函数,就像ASP.NET一样。

PHP: PHP:

...
function a($some_string){
return json_encode(array(
                "username" => "bob",
                "items" => array(
                        "item1" => "sandwich",
                        "item2" => "applejuice"
                )
        ));
}

JS: JS:

    $.ajax(
        {url:"index.php/a", 
        type:"POST",
        contentType:"application/json; charset=utf-8",
                    data:{some_string:"blabla"},
        dataType:"json",
        success:function(data){
            alert(data);
            },
        error:function(a,b,c){
            }
        });

In C#: 在C#中:

[WebMethod()]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static object a(string some_string)
{
  return new { 
                user_name = "bob", 
                items = new { 
                    item1 = "sanwitch", 
                    item2 = "applejuice" 
                    }
                };
        }

Thanks, 谢谢,
Péter 彼得

You can just put that one function in a PHP file alone. 您可以将一个函数单独放在PHP文件中。 Then run the function within that file (so it echoes out the JSON). 然后在该文件中运行该函数(因此它回显JSON)。 Have ajax call that file. 让ajax调用该文件。

In your case: 在你的情况下:

echo a($string);

If you were willing to explore an alternative to Jquery, there is a tool called XAJAX that allows you to directly call PHP functions asynchronously via AJAX. 如果您愿意探索Jquery的替代方法,那么有一个名为XAJAX的工具允许您通过AJAX异步直接调用PHP函数。 It's a pretty nifty tool, though the support and forums are a bit cryptic. 这是一个非常漂亮的工具,虽然支持和论坛有点神秘。 For those who are hardcore PHP (but not JAVASCRIPT) guys, this tool is a great option. 对于那些硬核PHP(但不是JAVASCRIPT)的人来说,这个工具是一个很好的选择。

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

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