javascript - 将来自 Web 服务的字符串转换为 JSON

标签 javascript php jquery json

我有到远程数据库的连接,并且我从数据库中获取了一些统计数据。所以我决定创建一个Web服务并通过它获取所需的数据。 DB服务器是Windows上的SQL Server,我需要在我的PHP网页中显示数据。

首先,我编写了返回字符串的 Web 服务

"[
  { 
    "name" : "John", 
    "Age":"54"
  }, 
  {
    "name":"Jack",
    "Age":"33"
  }
 ]"

我使用 PHP 的 file_get_contents() 方法获取了该字符串。

$json = file_get_contents('http://myurl.org/services.asmx/namelistJson');

但是一开始就返回了一些不需要的标签

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://myurl.org/services.asmx?op=namelistJson">

在最后

</string>

我用它来清洁它们

$json = strip_tags(file_get_contents('http://myurl.org/services.asmx/namelistJson'));

现在我有一个 json 字符串。

我想使用这个字符串作为 JavaScript 的 JSON 来创建一个表。

<?php

$json = strip_tags(file_get_contents('http://myurl.org/services.asmx/namelistJson'));

?>
<script>

    var response = $.parse(<?php echo $json; ?>);

    $.each(response, function(i, item) {
        $('<tr>')
                .html("<td>" + response[i].name + "</td>"
                        + "<td>" + response[i].Age + "</td>"
                        )
                .appendTo('#nameList');
    });

</script>

?>
<table id="nameList" class="table">
</table>

我收到有关缺少 ] 符号的错误。 FireBug 是这样说的

SyntaxError: missing ] after element list

如何正确地将字符串转换为 json 以便在 JavaScript 上使用它?

编辑:

如果我修改该行

var response = $.parse(<?php echo $json; ?>);

var response = <?php echo $json; ?>;

我仍然收到 ] 错误。

HTML 输出如下:

<script>

...

var response = [{"name" : "John",  "Age" : "14"},  {"name" : "40"}, ... ];

...

</script>

最佳答案

无需创建字符串然后再次将其转换为 json 对象,您可以直接从 webservice 发送 json 对象并直接在脚本(jquery)中使用它,如下所示:

下面是我的网络服务中的代码

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static object GetGridData() 
{
    DataTable dt = GetRecords(); // Fetch the data from sql in form of a datatable
    var returnData = from row in dt.AsEnumerable()
                     select new
                     {
                        Id = row["Id"]  // Here the Id in row["Id"] specifies the column in database
                         name = row["name"],
                         age = row["age"]
                     };
    return returnData;
}

要将其作为 jquery 中的对象访问,请使用以下代码:

 $.ajax({
                url: 'url of webservice along with method', 
                dataType: 'json',
                contentType: 'application/json; charset=utf-8;',
                tyep: 'GET',
                success: function (datas) {
                    var data = datas.d;
                        $.each(data, function (index, value) {
                        $('<tr>').html("<td>" + value.name + "</td>"+ "<td>" + value.Age + "</td>"
                    ).appendTo('#nameList');
                        });
                },
                error: function (error) {
                    alert('error occured');
                }
            });

但是如果你真的想使用字符串发送它并将其解析为 json 那么你可以使用

var jsonObject = JSON.parse(jsonstring);

否则您可以通过将 json 字符串粘贴到 jsonlint.com 来验证您的 json 字符串是否有效

希望这有帮助:)

关于javascript - 将来自 Web 服务的字符串转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25427499/

相关文章:

javascript - 使用 VueJS 2 在 Bootstrap 开关上触发事件

javascript - 向孙子添加事件处理程序

javascript - 根据数组元素生成复选框,然后根据选中的复选框填充另一个数组

javascript - jQuery JTable 如何拖动行

javascript - 从 Selenium 运行 javascript 时出现 "argument is not defined"错误

javascript - React 搜索过滤函数

javascript - 多个属性jquery

PHP 安全用户变量

php - Magento 1.9 fatal error Mage_Configurableswatches_Helper_Productimg' 找不到

javascript - 滚动到相对于 ID 的位置