php return response json

Return HTML in PHP JSON response

I am building an app to save small notes and comments. The app will require from you to submit a title and it will provide you a text area for your text.

I was thinking to return the pair through JSON, but someone told me that this is bad practice.

Is it really bad practice to return HTML through Jason and why?

4 Answers 4

JSON (JavaScript Object Notation) is a lightweight data-interchange format http://www.json.org/

The HTML DOM structure should be created and use JSON for exchanging data.

Once you’ve retrieved the data creating dynamic dom elements is fair game.

A few closely related questions:

As far as I know, it’s not bad practice to return a HTML string within a JSON object. The accepted answer for that second question seems to agree:

Request and return JSON for large datasets, but include the (escaped) HTML snippet for each record in the JSON record. This means more rendering time and more bandwidth use than (2), but can reduce duplication of often complex HTML rendering.

JOSN was made to overcome the bulky XML format used for data exchanging. It really is a light weight data-exchange format as described by James. Suppose: You need to display a dynamic list of products having all the info related to a product. If you return full HTML in the JSON its size is 2048 characters. But if you only return product name and realted info without the HTML markup then the response text string size will be less than 2048 characters, it can be 100 characters only because you are omitting the HTML markup which is not really required. SO you can just have the light-weight version of the data and then insert it in the HTML markup using client side script. This will make your application faster because you will have to wait less for the server response as the data size is small and transferring small amount of data(characters) will always be quicker than large data(characters).

XML contained heavy markup therefore JSON was looked as an alternative for faster data transfer.

php return response json. Смотреть фото php return response json. Смотреть картинку php return response json. Картинка про php return response json. Фото php return response json

It really depends on how you plan to implement your idea. As you mentioned JSON, my best guess is you are trying to implement AJAX. Well, while it’s possible to return almost any type of content encoded as a JSON object, I don’t see why you would need to send HTML elements like text-area from the server through JSON. AJAX is used for scenarios where a server request is made and the client wants to get the response without refreshing the page from which the request was sent. The most common usage is username and password validation on login pages.

I think you should get a clear picture of server-side scripting and client-side scripting. What you have already implemented using jquery is known as client-side scripting and that’s exactly how it should be done. As for fetching data from PHP, that’s done when you need to read some data from the database residing on the server. Say, the text-area is displayed only if a valid title, that has an entry in the database, has been entered. And I don’t see any requirement of that here.

Источник

Возвращение JSON из PHP-скрипта

Я хочу вернуть JSON из скрипта PHP.

Я просто повторяю результат? Должен ли я установить Content-Type заголовок?

Решение

Хотя обычно с этим у вас все нормально, вы можете и должны установить заголовок Content-Type:

Если я не использую конкретную платформу, я обычно позволяю некоторым параметрам запроса изменять поведение вывода. Это может быть полезно, как правило, для быстрого устранения неполадок, чтобы не отправлять заголовок или иногда print_r полезную нагрузку данных, чтобы увидеть его (хотя в большинстве случаев это не должно быть необходимо).

Другие решения

Полный фрагмент красивого и понятного PHP-кода, возвращающего JSON:

Согласно руководство по json_encode метод может вернуть не строку (ложный):

Возвращает JSON-кодированную строку в случае успеха или FALSE на провал.

json_encode например, потерпит неудачу (и вернется false ) если его аргумент содержит строку, отличную от UTF-8.

Это условие ошибки должно быть зафиксировано в PHP, например, так:

Тогда принимающая сторона, конечно же, должна осознавать, что присутствие jsonError свойство указывает на состояние ошибки, которое оно должно соответственно обработать.

В рабочем режиме может быть лучше отправить клиенту только общий статус ошибки и записать более конкретные сообщения об ошибках для дальнейшего изучения.

Установите тип контента с помощью header(‘Content-type: application/json’); а затем повторить ваши данные.

Также полезно установить безопасность доступа — просто замените * доменом, к которому вы хотите получить доступ.

Тип носителя MIME для текста JSON:
применение / JSON.

так что если вы установите заголовок для этого типа и выведите строку JSON, это должно работать.

сделаю работу. но имейте в виду, что:

У Ajax не возникнет проблем с чтением json, даже если этот заголовок не используется, за исключением случаев, когда ваш json содержит некоторые HTML-теги. В этом случае вам нужно установить заголовок как application / json.

Убедитесь, что ваш файл не закодирован в UTF8-BOM. Этот формат добавляет символ в верхней части файла, поэтому ваш вызов header () не удастся.

Источник

Return JSON response from AJAX using jQuery and PHP

JSON stands for JavaScript Object Notation, it is a data-interchange format which is also been used to passing data from the server.

It is the best and effective way when need to return multiple values as a response from the PHP script to the jQuery.

You couldn’t directly return an array from AJAX, it must have converted in the valid format.

In this case, you can either use XML or JSON format.

In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.

On the basis of response show data in tabular format.

php return response json. Смотреть фото php return response json. Смотреть картинку php return response json. Картинка про php return response json. Фото php return response json

Contents

1. Table structure

I am using users table in the tutorial example.

2. Configuration

Create config.php for database configuration.

Completed Code

3. HTML

Create a

for displaying user list using AJAX response.

Completed Code

4. PHP

Create ajaxfile.php file for handling AJAX request.

Completed Code

5. jQuery

On document ready state send an AJAX GET request.

Loop through all response values and append a new row to

on AJAX successfully callback.

Note – For handling JSON response you have to set dataType: ‘JSON’ while sending AJAX request.

Completed Code

6. Demo

7. Conclusion

In this tutorial, I showed how you can return the JSON response and handle it in jQuery AJAX.

You can convert the PHP array in JSON format with json_encode() function and return as a response. Set dataType: ‘JSON’ when send AJAX request.

If you found this tutorial helpful then don’t forget to share.

Источник

PHP JSON

last modified July 26, 2020

PHP JSON tutorial shows how to work with JSON in PHP.

The json_encode function returns the JSON representation of the given value. The json_decode takes a JSON encoded string and converts it into a PHP variable.

PHP frameworks such as Symfony and Laravel have built-in methods that work with JSON.

PHP JSON encode

In the following example, we use the json_encode function.

The example transforms a PHP array into a JSON string.

php return response json. Смотреть фото php return response json. Смотреть картинку php return response json. Картинка про php return response json. Фото php return response jsonFigure: JSON view in Firefox

Modern web browsers show JSON view for JSON data when they receive an appropriate content type in the header of the response.

PHP JSON decode

In the following example, we use the json_decode function.

The example transforms a JSON string into a PHP variable.

We start the server.

We send a GET request with curl.

PHP JSON read from file

In the following example, we read JSON data from a file.

This is the JSON data.

PHP JSON read from database

In the following example, we read data from an SQLite database and return it in JSON.

This SQL code creates a cities table in SQLite.

With the sqlite3 command line tool, we generate an SQLite database and create the cities table.

In the example, we retrieve the data from the database and return it as JSON.

PHP JSON and JS fetch API

In the following example, we use JavaScript fetch API to get the JSON data from a PHP script.

The JSON data is stored in a file.

We read the data and return it to the client.

We have a button in the document. When we click on the button, the fetch function retrieves JSON data from the data.php script. An HTML table is dynamically built and filled with the data.

php return response json. Смотреть фото php return response json. Смотреть картинку php return response json. Картинка про php return response json. Фото php return response jsonFigure: HTML table filled with JSON data from fetch API

PHP JSON in Slim

In the following example, we return JSON data from a Slim application.

We use the withJson method of the Response to return JSON data.

PHP JSON in Symfony

In the following example, we send a JSON response from a Symfony application.

A new application is created.

We set up a database URL for the SQLite database.

We create the database.

This is a command that creates the cities table in the database.

The command is executed.

PHP JSON in Laravel

In the following example, we send a JSON response from a Laravel application.

We create a new Laravel application.

We define the connection and the database file.

We create the database file.

A new migration for the cities table is created.

In the migration file, we create a schema for the cities table.

We run the migrations.

We create a data seeder for our database.

The seeder inserts eight rows into the table.

We execute the seeder.

Inside the route, we select all data from the database and return it as JSON with the json helper.

We run the web server.

We get the data with the curl tool.

PHP JSON from client

Symfony provides the HttpClient component which enables us to create HTTP requests in PHP. We can also send JSON data.

We install the symfony/http-client component.

The example sends a GET request with a JSON payload.

This is the output.

In this tutorial, we have worked with JSON data in plain PHP, Symfony, Slim, and Laravel.

Источник

Возврат JSON из PHP-скрипта

Я хочу вернуть JSON из PHP-скрипта.

15 ответов:

хотя вы обычно прекрасно обходитесь без него, вы можете и должны установить заголовок Content-Type:

Если я не использую определенную структуру, я обычно разрешаю некоторым параметрам запроса изменять поведение вывода. Это может быть полезно, как правило, для быстрого устранения неполадок, чтобы не отправлять заголовок, или иногда print_r полезных данных на глаз (хотя в большинстве случаев это не требуется).

полный кусок хорошего и ясного PHP кода, возвращающего JSON:

по словам инструкция о json_encode метод может возвращать не строку (ложные):

возвращает строку в кодировке JSON при успешном выполнении или FALSE на провал.

когда это происходит echo json_encode($data) выведет пустую строку, которая является недопустимый JSON.

json_encode например, сбой (и возврат false ) если его аргумент содержит строку не UTF-8.

эта ошибка условие должно быть записано в PHP, например так:

тогда принимающая сторона, конечно, должна знать, что присутствие jsonError свойство указывает на состояние ошибки, которое оно должно обрабатывать соответствующим образом.

в рабочем режиме может быть лучше отправить клиенту только общий статус ошибки и зарегистрировать более конкретные сообщения об ошибках для последующего исследования.

подробнее о работе с ошибками JSON в документация PHP.

Установите тип контента с помощью header(‘Content-type: application/json’); а затем Эхо ваши данные.

тип носителя MIME для текста JSON application / json.

поэтому, если вы установите заголовок для этого типа и выведите строку JSON, она должна работать.

сделает работу. но имейте в виду, что :

Ajax не будет иметь никаких проблем для чтения json, даже если этот заголовок не используется, за исключением того, если ваш json содержит некоторые HTML-теги. В этом случае вам нужно установить заголовок как application/json.

убедитесь, что ваш файл не закодирован в UTF8-BOM. Этот формат добавляет символ в верхней части файла, поэтому ваш вызов header() будет неудача.

Это простой PHP-скрипт для возврата мужского женского и пользовательского идентификатора, поскольку значение json будет любым случайным значением, как вы называете скрипт json.РНР.

надеюсь, что эта помощь спасибо

Если вам нужно получить json от php отправки пользовательской информации вы можете добавить это header(‘Content-Type: application/json’); прежде чем печатать любую другую вещь, так что вы можете распечатать вас custome echo ‘<"monto": "'.$monto[0]->valor.'»,»moneda»:»‘.$moneda[0]->nombre.'»,»simbolo»:»‘.$moneda[0]->simbolo.'»>’;

да,вам нужно будет использовать Эхо для отображения вывода. Mimetype: application / json

вы можете использовать этот маленькая PHP библиотека. Он отправляет заголовки и дает вам объект, чтобы использовать его легко.

да, просто установите соответствующий заголовок HTTP, Эхо результат, а затем выйти из сценария.

Если вы запрашиваете базу данных и вам нужен результирующий набор в формате JSON, это можно сделать следующим образом:

для помощи в разборе результата с помощью jQuery взгляните на в этом уроке.

простой способ форматирования объектов домена в JSON-использовать Маршал Сериализатор. Затем передайте данные в json_encode и отправить правильный заголовок типа контента для ваших нужд. При использовании фреймворков, таких как Symfony, вам не нужно заботиться о настройке заголовков вручную. Там вы можете использовать JsonResponse.

для всех других целей, таких как использование мобильного приложения application/json как тип контента.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *